
var JSonDtoModel = function(){
    this.state = 0;
    this.info = "成功";
    this.route = {};
    this.params = new Map();
    this.setState=function(state){
        this.state = state;
    };

    //set
    this.setInfo=function(info){
        this.info = info;
    };
    this.setState=function(state){
        this.state = state;
    };
    this.setParams=function(obj){
        this.params = new Map(obj);
    };

    // get

    this.getInfo=function(){
        return this.info;
    };

    this.getState=function(){
        return this.state;
    };
    this.getParams=function(){
        return this.params;
    };
    this.put=function(key,value){
        this.params.put(key,value);
    };

    this.get=function(key){
        return this.params.get(key);
    };
    this.clear = function(){
        this.state = 0;
        this.info = "成功";
        this.route = {};
        this.params = new Map();
    };
    this.setRoute = function(apiServer,call,description){
        if(arguments.length == 0){
            $.cc.error("路由信息错误");
            return;
        }
        var args = isArray(arguments[0]) ? arguments[0] : arguments;
        if(args.length == 1){
             call = args[0];
            this.route["call"]=call;
        }else if(args.length == 2){
             call = args[0];
             description = args[1];
            this.route["call"]=call;
            this.route["description"]=description;
        }else{
             apiServer = args[0];
             call = args[1];
             description = args[2];
            this.route["apiServer"]=apiServer;
            this.route["call"]=call;
            this.route["description"]=description;
        }
    };
    this.toJSONString=function(){
        var res = {};
        res["state"]=this.state;
        res["info"]=this.info;
        res["route"]=this.route;
        res["params"]=this.params.values();

        return JSON.stringify(res);
    };
    this.toString=function(){
        return this.toJSONString();
    };
};

JSonDtoModel.restore = function(str){
    var obj = JSON.parse(str);
    var dto = new JSonDtoModel();
    dto.setState(obj['state']);
    dto.setInfo(obj['info']);
    dto.setRoute(obj['route']);
    dto.setParams(obj['params']);

    return dto;
};

JSonDtoModel.clone = function(str){
    var dto = new JSonDtoModel();
    dto.setState(this.getState());
    dto.setInfo(this.getInfo());
    dto.setParams(this.getParams());
    return dto;
};

var _$ = CC = {};

$.extend($,{
    cc:CC
});

function getTopWindow(){
    var topWin=window;
    while(topWin.parent != topWin && isNotEmpty(topWin.parent.CC)){
        topWin = topWin.parent;
    }
    return topWin;
}

var notify = {};
$.extend(notify,{
    'notify':function(type,option){
        var opts = {
            position: 'top right',
            title:"提示"
        };
        if(isString(option)){
            opts["msg"] = option;
            Lobibox.notify(type,opts);
        }else{
           var options = $.extend(opts,option);
            Lobibox.notify(type,options);
        }

    },
    'info':function(option){
        this.notify("info",option);
    },
    'warning':function(option){
        this.notify("warning",option);
    },
    'error':function(option){
        this.notify("error",option);
    },
    'success':function(option){
        this.notify("success",option);
    }
});
$.extend(_$,{
    "notify":notify
});
$(document).ajaxSend(function(){
    if(isEmpty(window._PATH_LOAD_SUCCESS_) || window._PATH_LOAD_SUCCESS_){
        $('body').showLoading();
    }
}).ajaxSuccess(function(event,xhr,settrings){
    $('body').hideLoading();
}).ajaxError(function(event,xhr,settings){
    $('body').hideLoading();
    var httpStatus = xhr.status;
    $.cc.ajaxErrorHander(httpStatus);
});

$.extend(_$,{
layer:getTopWindow().layer,
    message:function(msg,callback,options){
        var _this =  this;

        _this.layer.alert(msg,options,function(index){
            if(callback){
                callback.call(null);
            }
            _this.layer.close(index);
        });
    },
    alert:function(){
        var _this =  this;
        var msg = arguments[0];
        var callback = isNotEmpty(arguments[1]) && isFunction(arguments[1])?arguments[1]:arguments[2];
        var options = isNotEmpty(arguments[1]) && !isFunction(arguments[1])?arguments[1]:arguments[2];
        var opts = {
            icon:6,
            title:'提示信息',
            offset:"30%"
        };
        $.extend(true,opts,options);
         _this.message(msg,callback,opts);
    },
    warn:function(){
        var _this =  this;
        var msg = arguments[0];
        var callback = isNotEmpty(arguments[1]) && isFunction(arguments[1])?arguments[1]:arguments[2];
        var options = isNotEmpty(arguments[1]) && !isFunction(arguments[1])?arguments[1]:arguments[2];
        var opts = {
            icon: 0,
            title:'警告信息',
            offset:"30%"
        };
        $.extend(true,opts,options);
        _this.message(msg,callback,opts);
    },
    error:function(){
        var _this =  this;
        var msg = arguments[0];
        var callback = isNotEmpty(arguments[1]) && isFunction(arguments[1])?arguments[1]:arguments[2];
        var options = isNotEmpty(arguments[1]) && !isFunction(arguments[1])?arguments[1]:arguments[2];
        var opts = {
            icon: 5,
            title:'错误信息',
            offset:"30%"
        };
        $.extend(true,opts,options);
        _this.message(msg,callback,opts);
    },
    close:function(index){
        var _this =  this;
        _this.layer.close(index);
    },
    confirm : function(msg,callbackOk,callbackCancel,options){
        var _this =  this;
        var opts = {
            icon: 3,
            title:'请选择',
            offset:"30%"
        };
        $.extend(true,opts,options);
        _this.layer.confirm(msg, opts, function(index){
            if(callbackOk){
                callbackOk.call(null);
            }
            _this.layer.close(index);
        }, function(index){
            if(callbackCancel){
                callbackCancel.call(null);
            }
            _this.layer.close(index);
        });
    },
    prompt:function(value,callback,options){
        var _this =  this;
        var opts = {
            title:'请输入',
            offset:"30%",
            formType:0
        };
        $.extend(true,opts,options);
        if(isNotEmpty(value)){
            opts["value"] = value;
        }
        _this.layer.prompt(opts,function(ok){
            if(callback){
                callback.call(null,ok);
            }
        });
    },
    tips:function(msg,selector,options){
        var _this =  this;
        var opts = {
            tips: [1, '#3595CC'],
            time: 4000
        };
        $.extend(opts,options);
        _this.layer.tips(msg,selector,opts);
    },
    load:function(type){
        var _this =  this;
        return _this.layer.load(type, {shade: 0.3,time:10*1000});
    },
    open:function(options){
        var _this =  this;
        var defaultConfig ={
            type : 2, //page层
            area : [  '1100px', "600px" ],
            offset: [ '50px'],
            shadeClose:false,
            maxmin : true,
            shade : 0.2, //遮罩透明度
            moveType : 1, //拖拽风格，0是默认，1是传统拖动
            success: function(layero, index){
                var win = getTopWindow();
                var iframeWin = win[layero.find('iframe')[0]['name']];
                iframeWin['p_Win'] = window;
                iframeWin['p_index'] = index;
            }
        };
        var opts = $.extend(true,defaultConfig,options);
        _this.layer.open(opts);
    },
    ajaxErrorHander:function(httpStatus,status){
        if("timeout" == status){
            _$.notify.error({
                "title":"timeout",
                "msg":"服务器繁忙,请稍后重试"
            });
            return;
        }

        if(httpStatus == 403){
            _$.notify.error({
                "title":403,
                "msg":"资源不可用"
            });
            return;
        }
        if(httpStatus == 404){
            _$.notify.error({
                "title":404,
                "msg":"无法找到指定位置的资源"
            });
            return;
        }
        if(httpStatus == 405){
            _$.notify.error({
                "title":405,
                "msg":"请求方法（GET、POST）类型对指定的资源不适用"
            });
            return;
        }
        if(httpStatus == 500){
            _$.notify.error("服务器内部错误,联系管理员");
            return;
        }
        if(httpStatus == 502){
            _$.notify.error("服务器由于维护或者负载过重未能应答");
            return;
        }
    },
    ajaxDtoRequestSync:function(inParams,options){
        var opt = {
            type: "POST",
            beforeSend:function(){
                return true;
            },
            contentType:'application/x-www-form-urlencoded',
            dataType : 'text',
            successHandler:function(result){
            }
        };

        $.extend(opt,options);
        var url = opt.url;
        var type = opt.type;
        var data = {
            "param":inParams.toJSONString()
        };
        var dataType = opt.dataType;
        var contentType = opt.contentType;
        var beforeSend = opt.beforeSend;
        var successHandler = opt.successHandler;
        var succFailHandler = opt.succFailHandler;
        var res;
        if(isEmpty(url)){
            return;
        }
        $.ajax({
            type: type,
            url:url,
            data: data,
            dataType: dataType,
            contentType: contentType,
            timeout:60000,
            async : false,
            beforeSend: beforeSend,
            success: function (responseText) {
                var result = JSonDtoModel.restore(responseText);

                var state = result.getState();
                var info = result.getInfo();
                if(state == 0){
                    res =  successHandler.call(window,result);
                }else{
                    if(isEmpty(info)){
                        _$.notify.error("空指针");
                    } else{
                        //succFailHandler.call(window,result);
                        successHandler.call(window,result);
                    }
                }
            }
        });
        return res;
    },
    ajaxDtoRequestSyncCommon:function(options){
        var callback;
        var opts = {
            url:"",
            successHandler:function(result){
                if(callback){
                    callback.call(null,result);
                }
            }
        };
        $.extend(opts,options);

        var route = opts.route;
        var data = opts.data;
        var url = opts.url;
        callback = opts.callback;

        var inParams = new JSonDtoModel();
        inParams.setParams(data);
        var apiServer=route['apiServer'];
        var call=route['call'];
        var description=route['description'];
        inParams.setRoute(apiServer,call,description);

        var config = {
            url:url,
            successHandler:callback
        };
        return  $.cc.ajaxDtoRequestSync(inParams,config);
    },
    ajaxDtoRequest:function(inParams,options){
        var opt = {
            type: "POST",
            beforeSend:function(){
                return true;
            },
            contentType:'application/x-www-form-urlencoded',
            dataType : 'text',
            successHandler:function(result){
            }
        };

        $.extend(opt,options);
        var url = opt.url;
        var type = opt.type;
        var data = {
            "param":inParams.toJSONString()
        };
        var dataType = opt.dataType;
        var contentType = opt.contentType;
        var beforeSend = opt.beforeSend;
        var successHandler = opt.successHandler;
        var succFailHandler = opt.succFailHandler;
        var res=0;
        if(isEmpty(url)){
            return;
        }
       return  $.ajax({
            type: type,
            url:url,
            data: data,
            dataType: dataType,
            contentType: contentType,
            timeout:60000,
            async : true,
            beforeSend: beforeSend,
            success: function (responseText) {
                var result = JSonDtoModel.restore(responseText);

                var state = result.getState();
                var info = result.getInfo();

                if(state == 0){
                    successHandler.call(window,result);
                }else{
                    if(isEmpty(info)){
                        _$.notify.error("空指针");
                    } else{
                        //succFailHandler.call(window,result);
                        successHandler.call(window,result);
                    }
                }
            }
        });
    },
    ajaxDtoRequestCommon:function(options){
        var callback;
        var opts = {
            url:"",
            successHandler:function(result){
                if(callback){
                    callback.call(null,result);
                }
            }
        };
        $.extend(opts,options);

        var route = opts.route;
        var data = opts.data;
        var url = opts.url;
         callback = opts.callback;

        var inParams = new JSonDtoModel();
        inParams.setParams(data);
        var apiServer=route['apiServer'];
        var call=route['call'];
        var description=route['description'];
        inParams.setRoute(apiServer,call,description);

        var config = {
            url:url,
            successHandler:callback
        };
      return  $.cc.ajaxDtoRequest(inParams,config);
    }
});


$.extend(_$,{
    getTarget:function(target){
        if(target.nodeType){
            return $(target);
        }else if(isString(target)){
            return $(target);
        }
        return target;
    },
    getFunctoin:function(fn,scope){
        var func;
        if(scope){
             func = scope[fn];
        }else{
            func = window[fn];
        }
        return func;
    },
    css : function(target, a) {
        var j = a.toLowerCase().split(";");
        for (var f = 0, d = j.length; f < d; f++) {
            var k = j[f];
            var m = k.split(":");
            if (m.length > 1) {
                if (m.length > 2) {
                    var h = m[0].trim();
                    m.removeAt(0);
                    var g = m.join(":").trim();
                    target.css(h, g);
                } else {
                    target.css(m[0].trim(), m[1].trim());
                }
            }
        }
    }
});

/**
 js面向对象语法
 */
$.extend(_$,{
    extend:function(childClass, parentClass, props) {
        var childProps = childClass.prototype, parentProps = parentClass.prototype;
        if (childClass.superclass == parentProps) {
            return;
        }

        childClass.superclass = parentProps;
        childClass.superclass.constructor = parentClass;

        for ( var key in parentProps) {
            childProps[key] = parentProps[key];
        }
        if (props) {
            for ( var key1 in props) {
                childProps[key1] = props[key1];
            }
        }
        return childClass;
    }
});




$.extend(_$,{
    components : {},
    uids:{},
    classes:{},
    _clsPre:"cc-",
    _uiPreCls:"ui-",
    reg:function(obj){
        if(obj === null || !obj.isComponent){
            return;
        }
        var id = obj.id;
        _$.components[id] = obj;
        var uid = obj.uid;
        _$.uids[uid] = obj;
    },
    unReg:function(obj){
        if(obj === null || !obj.isComponent ){
            return;
        }
        var id = obj.id;
        delete _$.components[id];
    },
    getById:function(id) {
        var obj = _$.components[id];
        return isEmpty(obj)?null:obj;
    },
    getByUId:function(uid) {
        var obj = _$.uids[uid];
        return isEmpty(obj)?null:obj;
    },
    regClass:function(pluginName,func){
        _$.parser.plugins.add(pluginName);
        if(!_$.classes[pluginName]){
            func.prototype.type = pluginName;
            _$.classes[pluginName] = func;
        }
    },
    getClass:function(pluginName){
        var func = _$.classes[pluginName];
        return isEmpty(func)?null:func;
    },
    findControls:function(context){
        var _this = this;
        if(context === null) {
            context = $("body");
        }
        var list=$("[class^='"+_this._uiPreCls+"']",context);
        var items = [];
        list.each(function(e){
            var obj = $(this);
            var uid = obj.attr("componentId");
            obj = _$.getByUId(uid);
            items.add(obj);
        });
        return items;
    }
});


$.extend(_$,{
    parser:{
        parseOptions: function(target,properties){

            var options = {};
            var s = $.trim(target.attr('data-options'));
            if (s){
                if (s.substring(0, 1) != '{'){
                    s = '{' + s + '}';
                }
                options = (new Function('return ' + s))();
            }

            $.map(['width','height','minWidth','maxWidth','minHeight','maxHeight'], function(p){
                var pv = $.trim(target[0].style[p] || '');
                if (pv){
                    if (pv.indexOf('%') == -1){
                        pv = parseInt(pv);
                        if (isNaN(pv)){
                            pv = undefined;
                        }
                    }
                    options[p] = pv;
                }
            });

            if (properties){
                var opts = {};
                for(var i=0; i<properties.length; i++){
                    var pp = properties[i];
                    if (typeof pp == 'string'){
                        opts[pp] = target.attr(pp);
                    } else {
                        for(var name in pp){
                            var type = pp[name];
                            if (type == 'boolean'  && isNotEmpty(target.attr(name))){
                                var val = target[0].getAttribute(name);
                                opts[name] = val ? (val == 'true') : false;
                            } else if (type == 'number' && isNotEmpty(target.attr(name))){
                                opts[name] = target.attr(name)=='0' ? 0 : parseFloat(target.attr(name)) ;
                            }else if (type == 'array'  && isNotEmpty(target.attr(name))){
                                var str = target.attr(name);
                                str = str.replaceAll("'","\"");
                                opts[name] = JSON.parse(str);
                            }
                            else if (type == 'json'){
                                var s = $.trim(target.attr(name));
                                if (s){
                                    if (s.substring(0, 1) != '{'){
                                        s = '{' + s + '}';
                                    }
                                    options[name] = (new Function('return ' + s))();
                                }else{
                                    options[name]={};
                                }
                            }else if(type == 'function'){
                                var s = $.trim(target.attr(name));
                                if(isNotEmpty(s)){
                                    var func = _$.getFunctoin(s);
                                    options[name]=func;
                                }
                            }
                            else if (type == 'object'){
                                var s = $.trim(target.attr(name));
                                if (s){
                                    options[name]=eval('(' + s + ')');
                                }
                            }
                        }
                    }
                }
                $.extend(options, opts);
            }

            return options;
        },
        auto: true,
        ids:[],
        count:0,
        onComplete: function(){
            logger("------onComplete---------");
        },
        onComponentComplete: function(id,type){
            var _this = this;
            _this.ids.remove(id);
            logger("***控件["+type+"]件完成,id[" + id+"]");
            if(_this.ids.length === 0){
                logger("***控件解析完成");
                _this.onComplete.call(_this);
            }
        },
        plugins:[],
        parse: function(context){
            if(isEmpty(context)) {
                context = $("body");
            }else if(isString(context)){
                context = $(context);
            }else if(context.nodeType){
                context = $(context);
            }
            if(isEmpty(context) && context.size() == 0) {
                return;
            }
            var _this = this;
            var components = {};
            for(var i=0; i<_this.plugins.length; i++){
                var name = _this.plugins[i];
                var list = $('.' + _$._clsPre + name, context);
                list.each(function(e){
                    var obj = $(this);
                    var id = obj.attr("id");
                    _this.count++;
                    _this.ids.add(id);
                });
                components[name] = list;
            }
            if(_this.count === 0){
                _$.parser.onComplete.call(_this);
                return;
            }
            logger("控件数 " + _this.count);
            for(var componentName in components){
                var list1 = components[componentName];
                if(list1.size() === 0){
                    continue;
                }

                logger("控件名称["+componentName+"],数量 " + list1.size());
                if(list1 !== null && list1.size()>0){

                    list1.each(function(){
                        var target = $(this);
                        var Func =  _$.getClass(componentName);
                        if(Func !== null){
                            new Func(target);
                        }
                    });
                }
            }
        }
    }
});



_$.Component = function(target){
    var _this = this;
    target = _$.getTarget(target);
    _this.events={};
    _this.el = target;
    _this.uid = uuid();
    _this.id = target.attr("id");

    var opts = _this._attrOpts();
    var properties = _this._attrProps();
    _this.options = $.extend(true,opts,_$.parser.parseOptions(target,properties));

    _$.reg(_this);
    _this._create();
};

_$.Component.prototype = {
    isComponent : true,
    id:"",
    uid:"",
    component:null,
    _cls:_$._clsPre + "component",
    _uiCls:_$._uiPreCls + "component",
    _create:function(){},
        _attrProps:function(){
        return ['id', 'remark'];
    },
    _attrOpts:function(){},
    _setStyle:function(){},
    _getEvents:function(keys){
        var _this = this;
        $.map(keys, function(p){
            var func = _this.getOption(p);
            if(isNotEmpty(func)){
                func = _$.getFunctoin(func);
                _this._on(p,func);
            }
        });
    },
    _loadSuccess:function(){
        var _this=this;
        _$.parser.onComponentComplete.call(_$.parser,_this.id,_this.type);
    },
    _bindEvents:function(){},
    _fire : function(type, e) {
        var _this = this;

        type = type.toLowerCase();
        var event = _this.events[type];
        if (event) {
            if (!e) {
                e = {};
            }
            if (e && e != _this) {
                e.source = _this;
                if (!e.type) {
                    e.type = type;
                }
            }
            for ( var c = 0, a = event.length; c < a; c++) {
                var item = event[c];
                if (item) {
                    item[0].apply(item[1], [ e ]);
                }
            }
        }
    },
    _on : function(type, fn, scope) {
        var _this = this;
        if (typeof fn == "string") {
            var func = _$.getFunctoin(fn,scope);
            if (func) {
                fn = func;
            }
        }
        if (typeof fn != "function" || !type) {
            return false;
        }
        type = type.toLowerCase();
        var event = _this.events[type];
        if (!event) {
            event = _this.events[type] = [];
        }
        scope = scope || _this;
        if (!_this._findListener(type, fn, scope)) {
            event.push([ fn, scope ]);
        }
        return _this;
    },
    _un : function(type, fn, scope) {
        var _this = this;
        if (typeof fn != "function") {
            return false;
        }
        type = type.toLowerCase();
        var event = _this.events[type];
        if (event) {
            scope = scope || _this;
            var item = _this._findListener(type, fn, scope);
            if (item) {
                event.remove(item);
            }
        }
        return _this;
    },
    _findListener : function(type, func, scope) {
        var _this = this;
        type = type.toLowerCase();
        scope = scope || _this;
        var event = _this.events[type];
        if (event) {
            for ( var i = 0; i < event.length ; i++) {
                var item = event[i];
                if (item[0] === func && item[1] === scope) {
                    return item;
                }
            }
        }
    },
    _replaceNode:function(source){
        var _this = this;
        var template = Handlebars.compile(source);
        var result = template(_this.options);
        var element = $(result);
        _this.el.replaceWith(element);
        _this.el = element;
        _this.el.attr("componentId",_this.uid);
    },
    setOption:function(key,value){
        var _this = this;
        _this.options[key]=value;
    },
    getOption:function(key){
        var _this = this;
        var value = _this.options[key];
        return value;
    },
    toString:function(){
        var _this = this;
        return _this.id;
    },
    destroy : function() {
        var _this = this;
        this.el.remove();
        _$.unReg(_this);
    }
};
/******************************************************验证规则*****************************************************/
$.extend(_$,{
    "validator":{
        execute:function(value,nameCn,rule){

            var _this = this;
            var type = rule["type"];
            var validMsg = isEmpty(rule["msg"]) ? _this.messages[type] : rule["msg"];
            var ruleValue = rule['value'];

            var handler = _this.methods[type];

            var params={
                "value":value,
                "nameCn":nameCn,
                "ruleValue":ruleValue,
                "validMsg":validMsg
            };


            return handler.call(null,params);

        },
        addMethod:function(name,func,msg){
            _$.validator.methods[name] = func;
            _$.validator.messages[name] = msg;

        },
        messages:{
            required: "必填",
            email: "必须是有效的电子邮件地址",
            password:"必须由6-20位字母数字组成",
            mobile:"必须是有效的手机号",
            tel:"必须是有效的座机号",
            url: "必须是有效的网址",
            account: "必须是由6-10位字母和数字组成",
            money:"必须是有效的金钱格式",
            number:"必须是数字",
            integer: "必须是正整数",
            positive: "必须是整数",
            natural:'必须是自然数',
            min: "必须大于{1}",
            minEq: "必须大于等于{1}",
            max: "必须小于{1}",
            maxEq: "必须小于等于{1}",
            minLength: "必须大于{1}个字符",
            maxLength: "必须小于{1}个字符",
            minLengthEq: "必须大于等于{1}个字符",
            maxLengthEq: "必须小于等于{1}个字符",
            rangeLength: "长度必须是大{1},小于{2}",
            rangeLengthEq: "长度必须是大于{1},小于等于{2}",
            range:"必须大于{1},小于{2}",
            rangeEq:"必须是大于等于{1},小于等于{2}",
            equalTo:"必须等于[{1}] "
        },
        format:function(source, params ) {
            var _this = this;
            if ( arguments.length === 1 ) {
                return function() {
                    var args = $.makeArray( arguments );
                    args.unshift( source );
                    return _this.format.apply( this, args );
                };
            }
            if ( arguments.length > 2 && params.constructor !== Array  ) {
                params = $.makeArray( arguments ).slice( 1 );
            }
            if ( params.constructor !== Array ) {
                params = [ params ];
            }
            $.each( params, function( i, n ) {
                source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {
                    return n;
                });
            });
            return source;
        },
        zeroHandler:function(params,func){

            var value=params["value"];
            var nameCn=params["nameCn"];
            var ruleValue=params["ruleValue"];
            var validMsg=params["validMsg"];

            var state = true;
            var info = "";

            if (isEmpty(value)) {
                state = true;
            }else{
                if (!func.call(null,value)) {
                    state = false;
                    var names = [nameCn]
                    info = _$.validator.format(validMsg, names);
                }
            }
            return {
                "state":state,
                "info":info
            };
        },
        oneHandler:function(params,func){
            var value=params["value"];
            var nameCn=params["nameCn"];
            var ruleValue=params["ruleValue"];
            var validMsg=params["validMsg"];

            var state = true;
            var info = "";

            if (isEmpty(value)) {
                state = true;
            }else{
                if (!func.call(null,value,ruleValue)) {
                    state = false;
                    var names = [nameCn,ruleValue]
                    info = _$.validator.format(validMsg, names);
                }
            }
            return {
                "state":state,
                "info":info
            };
        },
        twoHandler:function(params,func){

            var value=params["value"];
            var nameCn=params["nameCn"];
            var ruleValue=params["ruleValue"];
            var validMsg=params["validMsg"];
            var state = true;
            var info = "";

            if (isEmpty(value)) {
                state = true;
            }else{
                var arr = ruleValue.split(",");
                var min = arr[0];
                var max = arr[1];

                if (!func.call(null,value,min,max)) {
                    state = false;
                    var names = [nameCn,min,max]
                    info = _$.validator.format(validMsg, names);
                }
            }
            return {
                "state":state,
                "info":info
            };
        },
        methods: {
            'required': function (params) {

                var value=params["value"];
                var nameCn=params["nameCn"];
                var ruleValue=params["ruleValue"];
                var validMsg=params["validMsg"];

                var state = true;
                var info = "";

                if (isEmpty(value)) {
                    state = false;
                    var names = [nameCn]
                    info = _$.validator.format(validMsg, names);
                }

                return {
                    "state":state,
                    "info":info
                };
            },
            'email': function(params) {
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                    return reg.test(val);
                });
            },
            'password': function(params){
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^[A-Za-z0-9]{6,20}$/;
                    return reg.test(val);
                });
            },

            'mobile': function (params) {
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^1\d{10}$/;
                    return reg.test(val);
                });
            },
            'tel': function(params) {
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^0\d{2,3}-?\d{7,8}$/;
                    return reg.test(val);
                });
            },
            'url': function(params){
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
                    return reg.test(val);
                });
            },
            'account': function(params) {
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^[a-z0-9A-z]\w{5,9}$/;
                    return reg.test(val);
                });
            },
            'money': function(params){
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /(^-?[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
                    return reg.test(val);
                });
            },
            number: function(params) {
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^(\-|\+)?\d+(\.\d+)?$/;
                    return reg.test(val);
                });
            },
            'integer': function (params) {
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^[1-9]\d*$/;
                    return reg.test(val);
                });
            },
            'positive': function (params){
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^-?\d+$/;
                    return reg.test(val);
                });
            },
            'natural': function(params) {
                return  _$.validator.zeroHandler(params,function(val){
                    var reg = /^\d+$/;
                    return reg.test(val);
                });
            },
            'min': function(params) {
                return  _$.validator.oneHandler(params,function(val,num){
                    if (isNaN(val)) {
                        return false;
                    }
                    val = parseFloat(val);
                    if (val > num) {
                        return true;
                    }
                    return false;
                });
            },
            'minEq': function (params) {
                return  _$.validator.oneHandler(params,function(val,num){
                    if (isNaN(val)) {
                        return false;
                    }
                    val = parseFloat(val);
                    if (val >= num) {
                        return true;
                    }
                    return false;
                });
            },
            'max': function (params) {
                return  _$.validator.oneHandler(params,function(val,num){
                    if (isNaN(val)) {
                        return false;
                    }
                    val = parseFloat(val);
                    if (val < num) {
                        return true;
                    }
                    return false;
                });
            },
            'maxEq': function (params) {
                return  _$.validator.oneHandler(params,function(val,num){
                    if (isNaN(val)) {
                        return false;
                    }
                    val = parseFloat(val);
                    if (val <= num) {
                        return true;
                    }
                    return false;
                });
            },
            'minLength': function (params) {
                return  _$.validator.oneHandler(params,function(val,min){
                    var str = (val + "").trim();
                    if (str.length <= min) {
                        return false;
                    }
                    return true;
                });
            },
            'maxLength': function (params) {
                return  _$.validator.oneHandler(params,function(val,max){
                    var str = (val + "").trim();
                    if (str.length >= max) {
                        return false;
                    }
                    return true;
                });
            },

            'minLengthEq': function (params) {
                return  _$.validator.oneHandler(params,function(val,min){
                    var str = (val + "").trim();
                    if (str.length < min) {
                        return false;
                    }
                    return true;
                });
            },
            'maxLengthEq': function(params) {

                return  _$.validator.oneHandler(params,function(val,max){
                    var str = (val + "").trim();
                    if (str.length > max) {
                        return false;
                    }
                    return true;
                });
            },
            'rangeLength': function (params) {
                return  _$.validator.twoHandler(params,function(val,min,max){
                    var str = (val + "").trim();
                    if (str.length < max && str.length > min) {
                        return true;
                    }
                    return false;
                });
            },
            'rangeLengthEq': function (params) {
                return  _$.validator.twoHandler(params,function(val,min,max){

                    var str = (val + "").trim();
                    if (str.length <= max && str.length >= min) {
                        return true;
                    }
                    return false;
                });
            },
            'range': function (params) {
                return  _$.validator.twoHandler(params,function(val,min,max){
                    if (isNaN(val)) {
                        return false;
                    }
                    val = parseFloat(val);
                    if (val < max && val > min) {
                        return false;
                    }
                    return true;
                });
            },
            'rangeEq': function (params) {
                return  _$.validator.twoHandler(params,function(val,min,max){
                    if (isNaN(val)) {
                        return false;
                    }
                    val = parseFloat(val);
                    if (val <= max && val >= min) {
                        return false;
                    }
                    return true;
                });
            },
            'equalTo': function (params){
                var value=params["value"];
                var nameCn=params["nameCn"];
                var compareTo=params["ruleValue"];
                var validMsg=params["validMsg"];

                var objTo = _$.getById(compareTo)

                var valueTo = objTo.getValue();
                var nameCnTo = objTo.getOption("nameCn");

                var state = true;
                var info = "";

                if (isEmpty(value)) {
                    state = true;
                }else{
                    if (!(value == valueTo)) {
                        state = false;
                        var names = [nameCn,nameCnTo];
                        info = _$.validator.format(validMsg, names);
                    }
                }
                return {
                    "state":state,
                    "info":info
                };
             }
        }
    }
});

/*
 _$.validator.addMethod("xxxx",function(params){
 return  _$.validator.zeroHandler(params,function(val){
 if (isNaN(val)) {
 return false;
 }
 val = parseFloat(val);
 if (val > 10) {
 return true;
 }
 return false;
 });
 },"[{0}]这是一个测试校验");


 */
_$.Form=function(target){
    target = _$.getTarget(target);
    var _this = this;
    _this.el = target;

    var opts = {
    };
    _this.options = $.extend(true,opts);
};

_$.Form.prototype = {
    validState:true,
    clear:function(){
        var _this = this;
        var formItems =  _this.getFields(_this.el);
        if(formItems !== null  && formItems.length>0){
            for(var i=0;i<formItems.length;i++){
                var key = formItems[i];
                var obj = _$.getById(key);
                if(obj){
                    obj.setValue(null);
                }
            }
        }
    },
    reset:function(){
        var _this = this;
        _this.clear();
        var formItems =  _this.getFields(_this.el);
        if(formItems !== null  && formItems.length>0){
            for(var i=0;i<formItems.length;i++){
                var key = formItems[i];
                var obj = _$.getById(key);
                if(obj){
                    obj.reset();
                }
            }
        }
    },
    setValue:function(values,func){
        var _this = this;
        _this.clear();
        var formItems =  _this.getFields(_this.el);
        for(var i=0;i<formItems.length;i++){
            var obj = formItems[i];
            if(obj != null){

                var key = obj.getOption("name") || obj.id;
                var value = values[key];
                obj.setValue(value);
            }
        }
    },
    getValue:function(){
        var _this = this;
        var formItems =  _this.getFields(_this.el);
        var values = {};
        for(var i=0;i<formItems.length;i++){
            var obj = formItems[i];
            if(obj !== null){
                var value = obj.getValue();
                if(isNotEmpty(value)){
                    var name = obj.getOption("name") || obj.id;
                    values[name] = value;
                }
            }
        }
        return values;
    },
    getEditData:function(){
        var _this = this;
        var formItems =  _this.getFields(_this.el);
        var values = {};
        for(var i=0;i<formItems.length;i++){
            var key = formItems[i];
            var obj = _$.getById(key);
            if(obj !== null){
                obj.getEditValue(values);
            }
        }
        return values;
    },
    getAddData:function(){
        var _this = this;
        var values = {};
        var current = _this.getValue();
        for(var key in current){
            var c_val = current[key];
            if(isNotEmpty(c_val)){
                values[key] = c_val;
            }
        }
        return values;
    },
    getQueryData:function(){
        var _this = this;
        var formItems =  _this.getFields(_this.el);
        var values = {};
        for(var i=0;i<formItems.length;i++){
            var _id = formItems[i];

            if((_id+"").indexOf("_type") != -1){
                continue;
            }
            var obj = _$.getById(_id);
            if(obj != null){
                var value = obj.getValue();
                if(isNotEmpty(value)){
                    var name = obj.getOption("name") || _id;
                    values[name] = value;

                    var typeId = _id + "_type";
                    var typeObj = _$.getById(typeId);

                    if(typeObj!= null){
                        var typeValue = typeObj.getValue();
                        if(isNotEmpty(typeValue)){
                            var typeName = typeObj.getOption("name");
                            values[typeName] = typeValue;
                        }
                    }
                }
            }
        }
        return values;
    },
    getFields:function(){
        var _this = this;
        var items = _$.findControls(_this.el);

        var list = [];
        for(var i=0;i<items.length;i++){
            var item = items[i];
            if(item.isFormItem){
                list.add(item);
            }
        }
        return list;
    },
    setValid:function(flag){
        var _this = this;
        _this.validState = flag;
        var formItems = _this.getFields();
        for(var i=0;i<formItems.length;i++){
            var obj = formItems[i];
            obj.setValid(flag);
        }
    },
    isValid:function(){
        var _this = this;
        _this.validState = true;
        var formItems = _this.getFields();
        for(var i=0;i<formItems.length;i++){
            var obj = formItems[i];
            var flag = obj.isValid();
            if(_this.validState && !flag){
                _this.validState = flag;
            }
        }
        return _this.validState;
    }
};
var _EDITABLE_ = 1;
var _SHOW_ = 0;
_$.FormItem = function(target){
    var _this = this;
    _$.FormItem.superclass.constructor.call(_this,target);
};

_$.extend(_$.FormItem,_$.Component,{
    isFormItem:true,
    value:"",
    _uiCls:_$._uiPreCls + "FormItem",
    _cls:_$._clsPre + "formItem",
    _spanCls:_$._uiPreCls + "span",
    validState:true,
    initialization:false,
    errMsg:[],
    _create :function(){
        var _this = this;
        if(_this._isEdit()){
            _this._editModel();
        }else{
            _this._showModel();
        }
        _this.initialization=true;
        _this.el.attr("formId",_this.id);
    },
    _editModel:function(){
    },
    _showModel:function(){
        var _this = this;
        _this._clearEdit();
        var source='<div class="showDiv"></div>';
        _this._replaceNode(source);
        _this.component = $(".showDiv",_this.el);
        _this.el.addClass(_this._uiCls);
        _this.el.addClass(_this._spanCls);
        _this.setOption("model",_SHOW_);
        _this._init();
    },
    _clearShow:function(){
        var _this = this;
        if(_this.component){
            _this.component.remove();
        }
    },
    _clearEdit:function(){
        var _this = this;
        if(_this.component){
            _this.component.unbind();
            _this.component.remove();
        }
    },
    _init:function(){
        var _this = this;
        var initValue= _this.options["initValue"];
        if(isNotEmpty(initValue)){
            _this.setValue(initValue);
        }
        _this._loadSuccess();
    },
    _attrProps:function(){
        var _this = this;
        var properties = _$.FormItem.superclass._attrProps.call(_this);
        properties.addAll(['name',"qtype",'initValue','nameCn',"required-msg",{'required':'boolean',model: 'number',validRules:'json',"relationship":"array"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.FormItem.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            model:1
        });
    },
    _isEdit:function(){
        var _this = this;
        return _this.options.model == _EDITABLE_;
    },
    _sync:function(){
        var _this = this;
        _this.value =   _this.component.val();
    },
    _validateItem:function(rule){
        var _this = this;
        var value = _this.getValue();
        var nameCn = _this.getOption("nameCn");
        return  _$.validator.execute(value,nameCn,rule);
    },
    _showErrMsg:function(){
        var _this = this;
        $(".form_item_valid",_this.el).html( _this.errMsg.join(","));
    },
    _replaceNode:function(temp){
        var _this = this;
        var source='<div id="{{id}}" >'+ temp +'<p class="form_item_valid"></p><div class="form_item_memo">{{remark}}</div></div>';

        if(_this._isEdit()){
             source='<div id="{{id}}" >'+ temp +'<p class="form_item_valid"></p><div class="form_item_memo">{{remark}}</div></div>';
        }else{
             source='<div id="{{id}}" >'+ temp +'</div>';
        }
        var template = Handlebars.compile(source);
        var result = template(_this.options);
        var element = $(result);
        _this.el.replaceWith(element);
        _this.el = element;
        _this.el.attr("componentId",_this.uid);
    },
    reset:function(){
        var _this = this;
        var initValue = _this.getOption("initValue");
        _this.setValue(initValue);
    },
    setValue:function(value) {
        var _this = this;
        if(isEmpty(value)){
            _this.value = null;

            if (_this._isEdit()) {
                _this.component.val("");
            } else {
                _this.component.html("");
            }
        }else{
            _this.value = value;
            if (_this._isEdit()) {
                _this.component.val(value);
            } else {
                _this.component.html(value);
            }
        }
    },
    getValue:function(){
        var _this = this;
        if(_this._isEdit()){
            _this._sync();
        }
        return _this.value;
    },
    setValid:function(flag){
        var _this = this;
        _this.validState = flag;

        if(_this.validState){
            _this.errMsg=[];
        }
        this._showErrMsg();
    },
    validate:function (rules){
        var _this = this;
        var v_flag = true;
        var errMsg = [];

        if(isNotEmpty(rules) && rules.length >= 0){

            rules.each(function(rule){
                var res = _this._validateItem(rule);

                var state = res["state"];
                var info = res["info"];

                if(v_flag && !state){
                    v_flag = state;
                    errMsg.add(info);
                }
            });
        }

        return {
            "flag": v_flag,
            "errMsg": errMsg
        };
    },
    isValid:function(){
        var _this = this;

        if(!_this.el.is(":visible")){
            return true;
        }
        var validRules =_this.getOption("validRules");
        var nameCn = _this.getOption("nameCn");
        var required = _this.getOption("required");

        var required_msg = _this.getOption("required-msg");

        if(validRules){
            var rules = [];
            if(required == true){
                var required_rule = {};
                required_rule["type"] = "required";
                required_rule["value"] = validRules["required"];
                required_rule["msg"] = validRules["required-msg"];
                rules.add(required_rule);
            }


            for(var key in validRules){
                if(!key.endWith("msg")){
                    var rule = {};
                    rule["type"] = key;
                    rule["value"] = validRules[key];
                    rule["msg"] = validRules[key + "-msg"];

                    rules.add(rule);
                }
            }


            var res = _this.validate(rules);
            var flag = res.flag;
            _this.errMsg = res.errMsg;
            _this.setValid(flag);
            return flag;
        }
        return true;
    },
    getEditValue:function(values){
        var _this = this;
        var initValue = _this.getOption("initValue") ;
        var current = _this.getValue();

        var key =  _this.id;
        if(isEmpty(initValue) && isNotEmpty(current)){
            values[key] = current;
        }else if(isNotEmpty(initValue) && isEmpty(current)){
            values[key] = null;
        }else if(isNotEmpty(initValue) && isNotEmpty(current) && (initValue != current)){
            values[key] = current;
        }
    },
    setModel:function(model){
        var _this = this;

        if(_this.options.model == _SHOW_ && model == _EDITABLE_){
            _this._editModel();
        }else if(_this.options.model == _EDITABLE_ &&  model == _SHOW_){
            _this._showModel();
        }
    },
    _bindEvents:function(){
        var _this = this;
        _$.FormItem.superclass._getEvents.call(_this, ["onchange"]);
    },
    destroy : function() {
        var _this = this;
        if(_this._isEdit()){
            _this._clearEdit();
        }else{
            _this._clearShow();
        }
        _$.Text.superclass.destroy.call(_this);
    }
});
/******************************************************文本框*****************************************************/
_$.Text=function (target){
    var _this = this;
    _$.Text.superclass.constructor.call(_this,target);
};
_$.regClass("Text",_$.Text);

_$.extend(_$.Text,_$.FormItem, {
    _cls:_$._clsPre + "Text",
    _uiCls:_$._uiPreCls + "Text",
    _attrProps:function(){
        var _this = this;
        var properties = _$.Text.superclass._attrProps.call(_this);
        properties.addAll(["onfocus","oninput","onblur","onchange","inputStyle"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.Text.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            type:"text"
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();
        var source='<input type="{{type}}" class="Text" />';
        _this._replaceNode(source);
        _this.component = $(".Text",_this.el);
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    _bindEvents:function(){
        var _this = this;
        _$.Text.superclass._getEvents.call(_this, ["onfocus","oninput","onblur","onchange"]);
        if(_this._isEdit()){
            var event = {
                "name":_this.id
            };

            _this.component.bind("focus",function(e){
                event['source'] = _this.component;
                event['value'] = _this.getValue();
                _this._focusHandler(event);
            });
            _this.component.bind("input propertychange",function(){
                event['source'] = _this.component;
                event['value'] = _this.getValue();
                _this._inputHandler(event);
            });
            _this.component.bind("blur",function(){
                event['source'] = _this.component;
                event['value'] = _this.getValue();
                _this._blurHandler(event);
            });
        }
    },
    _blurHandler:function(event){
        var _this = this;
        _this._fire("onblur",event);
        var original = isNotEmpty(_this.original)?_this.original:_this.getOption("initValue");
        var value = _this.getValue();
        if(original != value){
            _this.original=value;
            _this._fire("onchange",event);
        }
    },
    _inputHandler:function(event){
        var _this = this;
        _this._fire("oninput",event)
    },
    _focusHandler:function(event){
        var _this = this;
       _this._fire("onfocus",event)
   },
    _setStyle:function(){
        var _this = this;
        var width = _this.getOption('width');
        if(isNotEmpty(width)){
            _this.component.css({
                "width":width + "px"
            });
        }
        var height =_this.getOption('height');
        if(isNotEmpty(height)){
            _this.component.css({
                "height":height + "px"
            });
        }
        var inputStyle = _this.getOption('inputStyle');
        if(isNotEmpty(inputStyle)){
            _$.css(_this.component,inputStyle)
        }
    }
});

/******************************************************隐藏域*****************************************************/
_$.Hidden=function (target){
    var _this = this;
    _$.Hidden.superclass.constructor.call(_this,target);
};
_$.regClass("Hidden",_$.Hidden);

_$.extend(_$.Hidden,_$.Text, {
    _cls:_$._clsPre + "Hidden",
    _uiCls:_$._uiPreCls + "Hidden",
    _create :function(){
        var _this = this;
        var source='<div id="{{id}}" ><input type="hidden" class="Hidden" /> </div>';

        var template = Handlebars.compile(source);
        var result = template(_this.options);
        var element = $(result);
        _this.el.replaceWith(element);
        _this.el = element;
        _this.el.attr("componentId",_this.uid);
        _this.el.addClass(_this._uiCls);

        _this.component = $(".Hidden",_this.el);
        _this._init();
    },
    setValue:function(value) {
        var _this = this;
        if(isEmpty(value)){
            _this.value = null;
            _this.component.val("");
        }else{
            _this.value = value;
            _this.component.val(value);
        }
    },
    getValue:function(){
        var _this = this;
        _this._sync();
        return _this.value;
    }
});

/******************************************************文本域*****************************************************/
_$.TextArea=function (target){
    var _this = this;
    _$.TextArea.superclass.constructor.call(_this,target);
};
_$.regClass("TextArea",_$.TextArea);

_$.extend(_$.TextArea,_$.Text, {
    _cls:_$._clsPre + "TextArea",
    _uiCls:_$._uiPreCls + "TextArea",
    _editModel:function(){
        var _this = this;
        _this._clearShow();

        var source='<textarea  type="{{type}}" class="TextArea"></textarea>';
        _this._replaceNode(source);
        _this.component = $(".TextArea",_this.el);
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    }
});

/******************************************************数字*****************************************************/
_$.Number=function (target){
    var _this = this;
    _$.Number.superclass.constructor.call(_this,target);
};
_$.regClass("Number",_$.Number);

_$.extend(_$.Number,_$.FormItem, {
    _cls:_$._clsPre + "Number",
    _uiCls:_$._uiPreCls + "Number",
    _editModel:function(){
        var _this = this;
        _this._clearShow();
        var source='<div class="Number"><span class="sub_num" >-</span><input type="text" class="num_inp" /><span class="add_num" >+</span></div>';
        _this._replaceNode(source);
        _this.component = $(".num_inp",_this.el);
        _this.subBtn = $(".sub_num",_this.el);
        _this.addBtn = $(".add_num",_this.el);
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    _clearEdit:function(){
        var _this = this;
        if( _this.addBtn){
            _this.addBtn.unbind();
            _this.addBtn.remove();
        }
        if(_this.subBtn){
            _this.subBtn.unbind();
            _this.subBtn.remove();
        }
        if(_this.component){
            _this.component.unbind();
            _this.component.remove();
        }
    },
    _attrProps:function(){
        var _this = this;
        var properties = _$.Number.superclass._attrProps.call(_this);
        properties.addAll(["onblur","onchange",{"numberType":"number","minNum":"number","maxNum":"number"}]);
        return properties;
    },
    _onblur:function(){
        var _this = this;
        _this._on("onblur", function(e){
            var value= e.value ;
            var numberType = _this.getOption("numberType");

            var reg;
            if(numberType == 0){
                reg = /^\d+$/;
            }else if(numberType == 1){
                reg = /^-?\d+$/;
            }else if(numberType == 2){
                reg = /^[1-9]\d*$/;
            }else if(numberType == 3){
                reg = /^-?\d+$/;
            }

            if(!reg.test(value)){
                _this.component.val(0);
            }
        });
    },
    _changNum: function(func){
        var _this = this;
        var val = _this.getValue();
        var num = parseInt(val);
        num = func.call(null,num);
        var numberType = _this.getOption("numberType");
        var minNum = _this.getOption("minNum");
        var maxNum = _this.getOption("maxNum");

        var reg;
        if(numberType == 0){
            reg = /^\d+$/;
        }else if(numberType == 1){
            reg = /^-?\d+$/;
        }else if(numberType == 2){
            reg = /^[1-9]\d*$/;
        }else if(numberType == 3){
            reg = /^-?\d+$/;
        }


        if(!reg.test(num+"") || (isNotEmpty(minNum) && num< minNum)  || (isNotEmpty(maxNum) && num > maxNum) ){
            _this.component.val(val);
        }else{
            _this.component.val(num);
        }
    },
    _onSubBtnClick:function(){
        var _this = this;
        _this.subBtn.bind("click",function(e){
            _this._changNum(function(num){
                num--;
                return num;
            });
        });
    },
    _onAddBtnClick:function(){
        var _this = this;
        _this.addBtn.bind("click",function(e){
            _this._changNum(function(num){
                num++;
                return num;
            });
        });
    },
    _bindEvents:function(){
        var _this = this;
        _$.Text.superclass._getEvents.call(_this, ["onblur","onchange"]);

        if(_this._isEdit()){
           _this._onblur();
            _this._onSubBtnClick();
            _this._onAddBtnClick();
            var event = {
                "name":_this.id
            };

            _this.component.bind("blur",function(){
                event['source'] = _this.component;
                event['value'] = _this.getValue();
                _this._blurHandler(event);
            });
        }
    },
    _blurHandler:function(event){
        var _this = this;
        _this._fire("onblur",event);
        var original = isNotEmpty(_this.original)?_this.original:_this.getOption("initValue");
        var value = _this.getValue();
        if(original != value){
            _this.original=value;
            _this._fire("onchange",event);
        }
    }
});

/******************************************************下拉框*****************************************************/
var hideComboPanel=function(comboId){
    var combo = _$.getById(comboId);
    var panel = $("#combo_panel_" + comboId);
    var combo_show = combo.combo_show;
    var multiple = combo.getOption("multiple");
    var speed = combo.getOption("speed");
    if(multiple || (isNotEmpty(combo.show_more) && combo.show_more.is(":visible"))){
        combo._hideMore();
    }

    combo_show.css({
        "border":"1px solid #ccc"
    });
    panel.slideUp(speed);

    if(!multiple) {
        combo.show_arrow.removeClass("icon_up").addClass("icon_down");
    }
};
var showComboPanel=function(comboId){

    var combo = _$.getById(comboId);
    var panel = $("#combo_panel_" + comboId);
    var multiple = combo.getOption("multiple");
    var speed = combo.getOption("speed");
    var combo_show = combo.combo_show;
    var panel_content = combo.panel_content;


    var panelWidth = combo.getOption("panelWidth");
    var panelHeight = combo.getOption("panelHeight");
    var realWidth,width,height;
    if(multiple){
        realWidth=combo_show.innerWidth();
    }else{
        realWidth=combo_show.innerWidth()-1;
    }
    panelWidth = isEmpty(panelWidth) || parseInt(panelWidth)<0 ? 0 : panelWidth;
    width  = panelWidth > realWidth?panelWidth:realWidth;
    width  = panelWidth < realWidth?realWidth:panelWidth;

    height =  isEmpty(panelHeight) || parseInt(panelHeight)<0 ? 200 : panelHeight;
    panel.width(width);
    panel_content.height(height);
    combo.setOption("panelHeight",height);

    $(".combo_panel").each(function(){
        var comboId2 = $(this).attr("comboId");
        hideComboPanel(comboId2);
    });
    combo_show.css({
        "border-bottom":"0px solid #ccc"
    });
    if(!multiple) {
        combo.show_arrow.removeClass("icon_down").addClass("icon_up");
    }
    panel.slideDown(speed);
    combo.panel_search.focus();
    combo.panel_search.val("");
    combo._searchByTxt("");
};

_$.Combo=function (target){
    var _this = this;
    _$.Combo.superclass.constructor.call(_this,target);
};
_$.regClass("Combo",_$.Combo);

_$.extend(_$.Combo,_$.FormItem, {
    _cls:_$._clsPre + "Combo",
    _uiCls:_$._uiPreCls + "Combo",
    _attrProps:function(){
        var _this = this;
        var properties = _$.Combo.superclass._attrProps.call(_this);
        properties.addAll(["onchange",{"multiple":"boolean","panelWidth":"number","panelHeight":"number"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.Combo.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "multiple":false,
            "defaultText":"==请选择==",
            "speed":50
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();

        var multiple = _this.getOption("multiple");
        if(!multiple){
            _this._createSingle();
        }else{
            _this._createMulti();
        }
        hideComboPanel(_this.id);
        _this._init();
        _this._bindEvents();
    },
    _createSingle:function(){
        var _this = this;

        var source='<div class="combo_single" >'+
            '<div class="combo_single_show">'+
            '<span type="text" class="combo_single_input"></span>' +
            '<i class="delete_icon"></i>'+
            '<i class="combo_single_arrow"></i>'+
            '</div> ' +
            '<div class="combo_panel" id="combo_panel_'+_this.id+'" comboId="'+_this.id+'">'+
            '<div class="combo_search">'+
            '<input type="text" class="combo_search_input"/>'+
            '<i class="combo_search_icon"></i>'+
            '</div>'+
            '<div class="combo_content"></div>'+
            '</div>'+
            '</div>';

        _this._replaceNode(source);
        _this.component = $(".combo_single",_this.el);
        _this.combo_show = $(".combo_single_show",_this.component);
        _this.combo_input = $(".combo_single_input",_this.component);
        _this.show_arrow = $(".combo_single_arrow",_this.component);
        _this.combo_delete = $(".delete_icon",_this.component);

        _this.panel = $(".combo_panel",_this.component);
        _this.panel_search = $(".combo_search_input",_this.panel);
        _this.panel_content = $(".combo_content",_this.panel);

        _this.component.attr("comboId",_this.id);
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._initPanel();
        _this._init();
        hideComboPanel(_this.id);
        _this._bindSingleEvents();

    },
    _createMulti:function(){
        var _this = this;
        var source = '<div class="combo_multi">'+
        '<div class="combo_multi_show">'+
        '<div class="combo_multi_input"></div>'+
        '<i class="combo_multi_more_bar icon_right"></i>'+
        '<div class="combo_multi_more"></div>'+
        '</div>'+
        '<div class="combo_panel" id="combo_panel_'+_this.id+'" comboId="'+_this.id+'">'+
        '<div class="combo_search">'+
        '<input type="text" class="combo_search_input"/>'+
        '<i class="combo_search_icon"></i>'+
        '</div>'+
        '<div class="combo_content"></div></div>'+
        '</div>';

        _this._replaceNode(source);
        _this.component = $(".combo_multi",_this.el);
        _this.combo_show = $(".combo_multi_show",_this.component);
        _this.combo_input = $(".combo_multi_input",_this.component);
        _this.show_more_bar = $(".combo_multi_more_bar",_this.component);
        _this.show_more = $(".combo_multi_more",_this.component);

        _this.panel = $(".combo_panel",_this.component);
        _this.panel_search = $(".combo_search_input",_this.panel);
        _this.panel_content = $(".combo_content",_this.panel);

        _this.component.attr("comboId",_this.id);
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._initPanel();
        _this._init();
        hideComboPanel(_this.id);
        _this._bindMultiEvents();

    },
    _bindSingleEvents:function(){
        var _this = this;
        var comboId = _this.id;
        _this.combo_show.click(function(e) {
            if(_this.panel.is(":visible")){
                hideComboPanel(comboId);
            }else{
                showComboPanel(comboId);
            }
            return false;
        });

        _this.combo_delete.click(function(){
            _this.setValue("");
            _this._searchByTxt("");
            return false;
        });
        $(document).click(function(e) {
            if($(e.target).closest("div.combo_panel").size()>0){
                return;
            }else{
                hideComboPanel( _this.id);
            }
        });
    },
    _bindMultiEvents:function(){
        var _this = this;
        var comboId = _this.id;
        _this.combo_input.click(function(e) {
            if(_this.panel.is(":visible")){
                hideComboPanel(comboId);
            }else{
                showComboPanel(comboId);
            }
            return false;
        });

        $(document).click(function(e) {
            if($(e.target).closest("div.combo_panel").size()>0 || $(e.target).closest("div.combo_multi_more").size()>0){

                return;
            }else{
                hideComboPanel( _this.id);
            }
        });
        _this.show_more_bar.click(function(){
            if(_this.show_more.is(":visible")){
                _this._hideMore();
            }else{
                _this._showMore();
            }
            return false;
        });
    },
    _hideMore:function(){
    },
    _showMore:function(){
    },
    _initPanel:function(){
    },
    _clearSingle:function(){
        var _this = this;
        if( _this.show_arrow){
            _this.show_arrow.unbind();
            _this.show_arrow.remove();
        }
        if( _this.combo_input){
            _this.combo_input.unbind();
            _this.combo_input.remove();
        }
        if( _this.combo_show){
            _this.combo_show.unbind();
            _this.combo_show.remove();
        }
        _this._clearPanel();
    },
    _clearMulti:function(){
        var _this = this;
        if( _this.show_more_bar){
            _this.show_more_bar.unbind();
            _this.show_more_bar.remove();
        }
        if( _this.show_more){
            _this.show_more.unbind();
            _this.show_more.remove();
        }
        if( _this.combo_input){
            _this.combo_input.unbind();
            _this.combo_input.remove();
        }
        if( _this.combo_show){
            _this.combo_show.unbind();
            _this.combo_show.remove();
        }
        _this._clearPanel();
    },
    _bindPanelEvents:function(){
        var _this = this;
        _this.panel_search.bind("input",function(e){
            var searchTxt = $(this).val();
            _this._searchByTxt(searchTxt);
            return false;
        });
    },
    _searchByTxt:function(searchTxt){
    },
    _setStyle:function(){
        var _this = this;
        var width = _this.getOption('width');


        if(isNotEmpty(width)){
            _this.combo_show.css({
                "width":width + "px"
            });
        }
        var height =_this.getOption('height');
        if(isNotEmpty(height)){
            _this.combo_show.css({
                "height":height + "px"
            });
        }
    }
});

/******************************************************下拉框*****************************************************/

_$.ComboBox=function (target){
    var _this = this;
    _$.ComboBox.superclass.constructor.call(_this,target);
};
_$.regClass("ComboBox",_$.ComboBox);

_$.extend(_$.ComboBox,_$.Combo, {
    _cls:_$._clsPre + "ComboBox",
    _uiCls:_$._uiPreCls + "ComboBox",
    data:[],
    _attrProps:function(){
        var _this = this;
        var properties = _$.ComboBox.superclass._attrProps.call(_this);
        properties.addAll(["apiServer","call","basePath","treeCall","idField","textField",'parentId','parentKey',"resultKey",{"params":"object","dataFilter":"function"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.ComboBox.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "idField":"id",
            "textField":"name",
            "resultKey":"list",
            'parentId':'',
            "apiServer":"base",
            "call":"",
            "basePath":"/base",
            "parentKey":"parentId",
            "dataFilter":function(list){
                return list;
            }
        });
    },
    _initPanel:function(){
       var _this = this;
        _this._initData();
    },
    _init:function(){
        var _this = this;
        if(!_this._isEdit()){
            _this._initShow();
        }
    },
    _initData:function(){
        var _this = this;
        var parentId = _this.getOption("parentId");
        if(isEmpty(parentId)){
            _this._loadData(_this._editInit);
        }else{
            var parentId = _this.getOption("parentId");
            var parentObj = _$.getById(parentId);
            parentObj._on("onchange", function(e){
                var parentValue = parentObj.getValue();
                _this._loadTree(parentValue,_this._editInit);
            });
        }
    },
    _initShow:function(){
        var _this = this;
        var parentId = _this.getOption("parentId");
        if(isEmpty(parentId)){
            _this._loadData(_this._showInit);
        }else{
            var parentObj = _$.getById(parentId);
            var parentValue = parentObj.getValue();
            _this._loadTree(parentValue,_this._showInit);
        }
    },
    _loadData:function(func){
    },
    _loadTree:function(value,func){
    },
    _editInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var list = result.get("list");
            var dataFilter = _this.getOption("dataFilter");
            list = dataFilter.call(window,list);
            _this.data = list;
            _this._setData(list);

            var initValue= _this.options["initValue"];
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if(isNotEmpty(initValue)){
                _this.setValue(initValue);
            }else{
                _this.value = null;
                _this.combo_input.html("");
            }
            _this._loadSuccess();
        }else{
            $.cc.error(info);
        }
    },
    _showInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var list = result.get("list");
            var dataFilter = _this.getOption("dataFilter");
            list = dataFilter.call(window,list);

            _this.data = list;
            var initValue = _this.getOption("initValue");
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if (isNotEmpty(initValue)){
                _this.setValue(initValue);
            }
            _this._loadSuccess();
        }else{
            $.cc.error(info);
        }
    },
    _searchByTxt:function(searchTxt){
        var _this = this;
        var multiple = _this.getOption("multiple");
        var textField = _this.getOption("textField");
        if(isEmpty(searchTxt)){
            _this._setData(_this.data);
        }else{
            var list = [];
            for(var i=0;i<_this.data.length;i++){
                var item = _this.data[i];
                if(item[textField].indexOf(searchTxt) != -1){
                    list.push(item);
                }
            }
            _this._setData(list);
        }
        _this.setValue(_this.value,false);
        _this.index = -1;
    },
    _setData:function(list){
        var _this = this;
        var multiple = _this.getOption("multiple");
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        $(".combobox_item",_this.panel_content).unbind();
        _this.panel_content.empty();

        if(list != null && list.size()>0){
            list.each(function(item,i){
                var id = item[idField];
                var name = item[textField];
                var _html = '<p class="combobox_item" data-value="'+id+'">'+name+'</p>';
                _this.panel_content.append(_html);
            });
        }
        if(!multiple){
            _this._bindSingleItemEvents();
        }else{
            _this._bindMultiIetmEvents();
        }
        _this._bindPanelEvents();
    },
    _bindPanelEvents:function(){
        var _this = this;
        var opts = _$.ComboBox.superclass._bindPanelEvents.call(_this);
        _this.index = -1;
        _this.panel.unbind('keyup').bind("keyup",function(e){
            var $combobox_items = $(".combobox_item",_this.panel_content);
            var len = $combobox_items.size();
            var panelHeight = _this.getOption("panelHeight");
            var cnt = (panelHeight % 50 == 0) ? panelHeight/50 : Math.floor(panelHeight/50) + 1;

            var code = event.keyCode;
            if(code == 38){
                if (_this.index<=0) {
                    _this.index = len;
                }
                _this.index--;
                var $combobox_item = $combobox_items.eq(_this.index);
                $combobox_item.addClass("combo_selected").siblings().removeClass("combo_selected");

                _this.panel_content.animate({scrollTop:(_this.index -cnt)*25},100);
            }else if(code == 40){
                _this.index++;
                if (_this.index>=len) {
                    _this.index = 0;
                }

                var $combobox_item = $combobox_items.eq(_this.index);
                $combobox_item.addClass("combo_selected").siblings().removeClass("combo_selected");

                _this.panel_content.animate({scrollTop:(_this.index -cnt)*25},100);
            }else if(code == 13){
                var val =  $combobox_items.eq(_this.index).attr("data-value");
                _this.setValue(val);
                hideComboPanel(_this.id);
            }
            return false;
        });
    },
    _bindSingleItemEvents:function(){
        var _this = this;
        $(".combobox_item",_this.panel_content).unbind("click").bind("click",function(){
            var val = $(this).attr("data-value");
            _this.setValue(val);
            hideComboPanel(_this.id);
            return false;
        });
    },
    _bindMultiIetmEvents:function(){
        var _this = this;
        $(".combobox_item",_this.panel_content).unbind("click").bind("click",function(){
            var val = $(this).attr("data-value");
            var value = _this.getValue();
            var values = [];
            if(isNotEmpty(value)){
                values = (value+"").split(",");
            }

            if(values.indexOf(val) == -1){
                values.add(val);
            }else{
                values.remove(val);
            }
            _this.setValue(values.join(","));
            return false;
        });
    },
    _clearPanel:function(){
        var _this = this;
        if( _this.panel_content){
            _this.panel_content.unbind();
            _this.panel_content.remove();
        }
        if( _this.panel_search){
            _this.panel_search.unbind();
            _this.panel_search.remove();
        }

        if( _this.panel){
            _this.panel.unbind();
            _this.panel.remove();
        }
    },
    setValue:function(value,change) {
        var _this = this;
        if(isEmpty(change)){
            change = true;
        }

        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");
        var multiple = _this.getOption("multiple");

        if(isEmpty(value) || isEmpty(_this.data) || _this.data.length == 0){
            _this.value = null;
            if (_this._isEdit()) {
                _this.combo_input.html("");
            } else {
                _this.component.html("");
            }
        }else{
            _this.value = value;
            if (_this._isEdit()) {
                if(!multiple){
                    $(".combobox_item",_this.panel_content).each(function(){
                        var val = $(this).attr("data-value");
                        $(this).removeClass("combobox_item_selected");
                    });


                    var flag = _this.data.some(function(item,i){
                        var id = item[idField];
                        var name = item[textField];

                        if(id == value){
                            $(".combobox_item[data-value='"+value+"']",_this.panel_content).each(function(){
                                $(this).addClass("combobox_item_selected");
                            });
                            _this.combo_input.html(name);
                            return true;
                        }
                        return false;
                    });

                    if(!flag){
                        _this.value = null;
                        _this.combo_input.html("");
                    }
                }else{
                    var values = (value+"").split(",");
                    if(values != null && values.length>0){
                        var names=[] ;
                        for(var i=0;i<values.length;i++){
                            var itemValue = values[i];

                            _this.data.each(function(item,i){
                                var id = item[idField];
                                var name = item[textField];
                                if(id == itemValue){
                                    names.add(name);
                                }
                            });
                        }
                        if(names.length>0){
                            _this.combo_input.html(names.join(","));
                        }else{
                            _this.value = null;
                            _this.combo_input.html('');
                        }

                        var arr = _this.data.filter(function(item,index){
                            for(var i=0;i<values.length;i++){
                                if(item[idField] == values[i]){
                                    return false;
                                }
                            }
                            return true;
                        });
                        _this._setData(arr);
                    }else{
                        _this.value = null;
                        _this.combo_input.html('');
                    }
                }
            } else {
                if(!multiple){
                    var flag = _this.data.some(function(item,i){
                        var id = item[idField];
                        var name = item[textField];

                        if(id == value){
                            _this.component.html(name);
                            return true;
                        }
                        return false;
                    });
                    if(!flag){
                        _this.value = null;
                        _this.component.html("");
                    }
                }else{
                    var values = (value+"").split(",");
                    if(values.length>0){
                        var names=[] ;
                        for(var i=0;i<values.length;i++){
                            var itemValue = values[i];

                            _this.data.each(function(item,i){
                                var id = item[idField];
                                var name = item[textField];
                                if(id == itemValue){
                                    names.add(name);
                                }
                            });
                        }
                        if(names.length>0){
                            _this.component.html(names.join(","));
                        }else{
                            _this.value = null;
                            _this.component.html('');
                        }
                    }else{
                        _this.value = null;
                        _this.component.html('');
                    }
                }
            }
        }
        if(change){
            _this._fire("onchange");
        }
    },
    _hideMore:function(){
        var _this = this;
        var multiple = _this.getOption("multiple");
        if(multiple){
            _this.show_more_bar.addClass("icon_right").removeClass("icon_left");
            _this.show_more.empty();
            _this.show_more.hide();
        }
    },
    _showMore:function(){
        var _this = this;
        var multiple = _this.getOption("multiple");
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");
        if(multiple){
            hideComboPanel(_this.id);
            _this.show_more_bar.addClass("icon_left").removeClass("icon_right");
            _this.show_more.empty();
            _this.show_more.show();

            if(isNotEmpty(_this.value)){
                var values = (_this.value+"").split(",");
                var names = [];
                values.each(function(val){
                    _this.data.each(function(item){
                        if(val == item[idField]){
                            names.add(item[textField]);
                        }
                    });
                });

                if(values.length>0){
                    for(var i=0;i<values.length;i++){
                        var id = values[i];
                        var name = names[i];
                        var _html='<div class="data_item" ><span>'+name+'</span><i class="deleteicon" data-value="'+id+'"></i></div>';
                        _this.show_more.append(_html);
                    }

                    $(".data_item .deleteicon",_this.show_more).click(function(){
                        var val = $(this).attr("data-value");
                        if(values.indexOf(val) != -1){
                            values.remove(val);
                            _this.setValue(values.join(","));
                            var item = $(this).closest(".data_item");
                            $(this).unbind();
                            item.remove();
                        }
                        return false;
                    });
                }
            }
        }
    },
    getValue:function(){
        var _this = this;
        return _this.value;
    }
});

/******************************************************下拉框*****************************************************/

_$.ComboData=function (target){
    var _this = this;
    _$.ComboData.superclass.constructor.call(_this,target);
};
_$.regClass("ComboData",_$.ComboData);

_$.extend(_$.ComboData,_$.ComboBox, {
    _cls:_$._clsPre + "ComboData",
    _uiCls:_$._uiPreCls + "ComboData",
    dataList:[],
    _attrProps:function(){
        var _this = this;
        var properties = _$.ComboData.superclass._attrProps.call(_this);
        properties.addAll([{"data":"object"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.ComboData.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{ 
            'data':{}
        });
    },
    _initShow:function(value){
        var _this = this;
        var list = _this.getOption("data");
        _this.data = list;
        var initValue= _this.options["initValue"];
        if(isNotEmpty(_this.value)){
            _this.setValue(_this.value);
        }else{
            _this.setValue(initValue);
        }
        _this._loadSuccess();
    },
    _initPanel:function(){
        var _this = this;
        var list = _this.getOption("data");
        _this.data = list;
        _this._setData(list);
        var initValue= _this.options["initValue"];
        if(isNotEmpty(_this.value)){
            _this.setValue(_this.value);
        }else{
            _this.setValue(initValue);
        }
        _this._bindPanelEvents();
        _this._loadSuccess();
    }
});

/******************************************************下拉框*****************************************************/

_$.ComboDict=function (target){
    var _this = this;
    _$.ComboDict.superclass.constructor.call(_this,target);
};
_$.regClass("ComboDict",_$.ComboDict);

_$.extend(_$.ComboDict,_$.ComboBox, {
    _cls:_$._clsPre + "ComboDict",
    _uiCls:_$._uiPreCls + "ComboDict",
    _attrProps:function(){
        var _this = this;
        var properties = _$.ComboDict.superclass._attrProps.call(_this);
        properties.addAll(["dictCode"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.ComboDict.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            'dictCode':'',
            "idField":"code",
            "call":"dict.selectByDict"
        });
    },
    _loadData:function(func){
        var _this = this;
        var parentKey = _this.getOption("parentKey");
        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var dictCode = _this.getOption("dictCode");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");
        var params = _this.getOption("params");
        if(params == null){
            params = {};
        }
        params["dictCode"]=dictCode;

        if(_this._isEdit()){
            $(".combobox_item",_this.panel_content).unbind();
            _this.panel_content.empty();
        }

        _this.data = [];
        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询下拉框条目"
        };

        var url= basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    }
});

/******************************************************下拉框*****************************************************/

var onComboTreeClick = function(event, treeId, treeNode) {

    var panel = $(event.target).closest("div.combo_panel");
    if(panel.size()>0){
        var comboId = panel.attr("comboId");
        var combo = _$.getById(comboId);
        if(treeNode){
            var treeObj = $.fn.zTree.getZTreeObj(treeId);

            var parentKey = combo.getOption("parentKey");
            var idField = combo.getOption("idField");
            var textField = combo.getOption("textField");
            var multiple = combo.getOption("multiple");

           if(!multiple) {
               var code = treeNode[idField];
               combo.setValue(code);
               hideComboPanel(comboId);
           }
        }
    }
};
var onComboTreeCheck = function(event, treeId, treeNode) {

    var panel = $(event.target).closest("div.combo_panel");
    if(panel.size()>0){
        var comboId = panel.attr("comboId");
        var combo = _$.getById(comboId);
        if(treeNode){
            var treeObj = $.fn.zTree.getZTreeObj(treeId);

            var parentKey = combo.getOption("parentKey");
            var idField = combo.getOption("idField");
            var textField = combo.getOption("textField");
            var multiple = combo.getOption("multiple");

            if(multiple) {
                var code = treeNode[idField];
                var checked = treeNode.checked;
                var value = combo.value;
                var values = [];
                if(isNotEmpty(value)){
                    values = (value+"").split(",");
                }
                if(checked){
                    if(values.indexOf(code) == -1){
                        values.add(code);
                        combo.setValue(values.join(","));
                    }
                }else{
                    if(values.indexOf(code) != -1){
                        values.remove(code);
                        combo.setValue(values.join(","));
                    }
                }

            }
        }
    }
};

_$.ComboTree=function (target){
    var _this = this;
    _$.ComboTree.superclass.constructor.call(_this,target);
};
_$.regClass("ComboTree",_$.ComboTree);

_$.extend(_$.ComboTree,_$.Combo, {
    _cls:_$._clsPre + "ComboTree",
    _uiCls:_$._uiPreCls + "ComboTree",
    _attrProps:function(){
        var _this = this;
        var properties = _$.ComboTree.superclass._attrProps.call(_this);
        properties.addAll(["basePath","parentKey","dictCode","apiServer","call"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.ComboTree.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            'dictCode':'',
            "idField":"id",
            "textField":"name",
            "parentKey":"parentId",
            "leaf":"leaf",
            "level":"level",
            "namePath":"namePath",
            "basePath":"/base",
            "apiServer":"base",
            "call":"dict.selectNodes"
        });
    },
    _init:function(){
        var _this = this;
        if(!_this._isEdit()){
            _this._initShow();
        }
    },
    _initShow:function(){
        var _this = this;
        _this._loadData(_this._showInit);
    },

    _initPanel:function(){
        var _this = this;
        _this._initData();
    },
    _initData:function(){
        var _this = this;
        _this._loadData(_this._editInit);
        _this._bindPanelEvents();
    },
    _loadData:function(func){
        var _this = this;

        var parentKey = _this.getOption("parentKey");
        var dictCode = _this.getOption("dictCode");
        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");

        var params = {
            dictCode:dictCode
        };

        if(_this._isEdit()){
            $(".combobox_item",_this.panel_content).unbind();
            _this.panel_content.empty();
        }
        _this.data = [];

        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询树形"
        };

        var url=basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    },
    _editInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var list = result.get("list");
            _this.data = list;
            _this._setData(list);
            var initValue= _this.options["initValue"];
            _this.setValue(initValue);
        }else{
            $.cc.error(info);
        }
    },
    _setData:function(list){
        var _this = this;
        var parentKey = _this.getOption("parentKey");
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");
        var basePath = _this.getOption("basePath");
        var multiple = _this.getOption("multiple");

       if(list != null && list.length>0){

           $(".combobox_item",_this.panel_content).unbind();
           _this.panel_content.empty();

           var _html = '<div id="tree_'+_this.id+'" class="ztree"></div>';
           _this.panel_content.append(_html);

           if(!multiple){
               var setting = {
                   data: {
                       simpleData: {
                           enable: true,
                           idKey: idField,
                           pIdKey: parentKey,
                           name:textField
                       }
                   },
                   callback: {
                       onClick: onComboTreeClick
                   },
                   view: {
                       showLine:false
                   }
               };
               $.fn.zTree.init($("#tree_"+_this.id), setting, list);
           }else{
               var setting = {
                   data: {
                       simpleData: {
                           enable: true,
                           idKey: idField,
                           pIdKey: parentKey,
                           name:textField
                       }
                   },
                   callback: {
                       onCheck: onComboTreeCheck
                   },
                   check: {
                       enable: true,
                       chkboxType: { "Y": "", "N": "" }
                   },
                   view: {
                       showLine:false
                   }
               };
               $.fn.zTree.init($("#tree_"+_this.id), setting, list);
           }
       }
        _this._loadSuccess();
    },
    _showInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var list = result.get("list");
            _this.data = list;

            var initValue= _this.options["initValue"];
            var idField= _this.options["idField"];
            var textField= _this.options["textField"];

            if(initValue != null){
                var values = (initValue+"").split(",");
                if(values.length>0) {
                    var names = [];
                    for (var i = 0; i < values.length; i++) {
                        var itemValue = values[i];

                        list.each(function (item, i) {
                            var id = item[idField];
                            var name = item[textField];
                            if (id == itemValue) {
                                names.add(name);
                            }
                        });
                    }
                    if (names.length > 0) {
                        _this.value = values.join(",");

                        if (_this._isEdit()) {
                            _this.combo_input.html(names.join(","));
                        } else {
                            _this.component.html(names.join(","));
                        }
                    } else {
                        _this.value = null;

                        if (_this._isEdit()) {
                            _this.combo_input.html('');
                        } else {
                            _this.component.html('');
                        }
                    }
                }
            }


        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    getValue:function(){
        var _this = this;
        return _this.value;
    },
    setValue:function(value,change){
        var _this = this;
        if(isEmpty(change)){
            change = true;
        }


        if(isEmpty(value) || isEmpty(_this.data) || _this.data.length == 0){
            _this.value = null;
            if (_this._isEdit()) {
                _this.combo_input.html("");
            } else {
                _this.component.html("");
            }
        }else{
            var multiple = _this.getOption("multiple");
            var idField = _this.getOption("idField");
            var textField = _this.getOption("textField");

            if(!multiple){

                var flag = _this.data.some(function(item,i){
                    var id = item[idField];
                    var name = item[textField];

                    if(id == value){
                        _this.value = id;

                        if (_this._isEdit()) {
                            _this.combo_input.html(name);
                        } else {
                            _this.component.html(name);
                        }
                        return true;
                    }
                    return false;
                });

                if(!flag){
                    _this.value = null;
                    if (_this._isEdit()) {
                        _this.combo_input.html("");
                    } else {
                        _this.component.html("");
                    }
                }
            }else{
                var values = (value+"").split(",");
                if(values.length>0){
                    var names=[] ;
                    for(var i=0;i<values.length;i++){
                        var itemValue = values[i];

                        _this.data.each(function(item,i){
                            var id = item[idField];
                            var name = item[textField];
                            if(id == itemValue){
                                names.add(name);
                            }
                        });
                    }
                    if(names.length>0){
                        _this.value = values.join(",");

                        if (_this._isEdit()) {
                            _this.combo_input.html(names.join(","));
                        } else {
                            _this.component.html(names.join(","));
                        }
                    }else{
                        _this.value = null;

                        if (_this._isEdit()) {
                            _this.combo_input.html('');
                        } else {
                            _this.component.html('');
                        }
                    }

                    var treeObj = $.fn.zTree.getZTreeObj("tree_" + _this.id);
                    treeObj.checkAllNodes(false);

                    values.each(function(val){
                        var node = treeObj.getNodeByParam(idField,val, null);

                        treeObj.checkNode(node, true, false);
                    });
                }
            }
        }

        if(change){
            _this._fire("onchange");
        }
    },
    _hideMore:function(){
        var _this = this;
        var multiple = _this.getOption("multiple");
        if(multiple){
            _this.show_more_bar.addClass("icon_right").removeClass("icon_left");
            _this.show_more.empty();
            _this.show_more.hide();

        }
    },
    _showMore:function(){
        var _this = this;
        var multiple = _this.getOption("multiple");
        if(multiple){
            hideComboPanel(_this.id);
            _this.show_more_bar.addClass("icon_left").removeClass("icon_right");
            _this.show_more.empty();
            _this.show_more.show();

            if(isNotEmpty(_this.value)){
                var values = (_this.value+"").split(",");
                var names = [];

                if(values.length>0){
                    for(var i=0;i<values.length;i++){
                        var id = values[i];
                        var name = names[i];
                        var _html='<div class="data_item" ><span>'+name+'</span><i class="deleteicon" data-value="'+id+'"></i></div>';
                        _this.show_more.append(_html);
                    }

                    $(".data_item .deleteicon",_this.show_more).click(function(){
                        var val = $(this).attr("data-value");

                        if(values.indexOf(val) != -1){
                            values.remove(val);
                            _this.setValue(values.join(","));
                            var item = $(this).closest(".data_item");
                            $(this).unbind();
                            item.remove();
                        }
                        return false;
                    });
                }
            }
        }
    }
});


/******************************************************下拉框*****************************************************/
_$.Popup=function (target){
    var _this = this;
    _$.Popup.superclass.constructor.call(_this,target);
};
_$.regClass("Popup",_$.Popup);

_$.extend(_$.Popup,_$.FormItem, {
    _cls:_$._clsPre + "Popup",
    _uiCls:_$._uiPreCls + "Popup",
    _attrProps:function(){
        var _this = this;
        var properties = _$.Popup.superclass._attrProps.call(_this);
        properties.addAll(["onchange","url"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.Popup.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{

        });
    },
    _sync:function(){
        var _this = this;
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();
        var source= '<div class="popup"><span type="text" class="popup_input" value="AAA"></span><i class="popup_bar">...</i></div>';

        _this._replaceNode(source);
        _this.component = $(".popup",_this.el);
        _this.popup_input = $(".popup_input",_this.component);
        _this.popup_bar = $(".popup_bar",_this.component);
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this._initDialog();
        if(!_this.initialization) {
            _this._init();
        }else{
            _this.setValue(_this.value);
        }
        _this._bindEvents();
    },
    _initDialog:function(){
    },
    _setStyle:function(){
        var _this = this;
        var width = _this.getOption('width');
        if(isNotEmpty(width)){
            _this.component.css({
                "width":width + "px"
            });
        }
    }
});

/******************************************************下拉框*****************************************************/
_$.PopupIconCls=function (target){
    var _this = this;
    _$.PopupIconCls.superclass.constructor.call(_this,target);
};
_$.regClass("PopupIconCls",_$.PopupIconCls);

_$.extend(_$.PopupIconCls,_$.Popup, {
    _cls:_$._clsPre + "PopupIconCls",
    _uiCls:_$._uiPreCls + "PopupIconCls",
    _attrProps:function(){
        var _this = this;
        var properties = _$.PopupIconCls.superclass._attrProps.call(_this);
        properties.addAll(["onchange","url"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.PopupIconCls.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "path":"/lib/cc",
            "url":"/html/iconCls.html"
        });
    },
    _initDialog:function(){
        var _this = this;
        _this.popup_bar.click(function(){
            var path = _this.getOption("path");
            var url = _this.getOption("url");

            url = path + url;
            var width = '400px';
            var height = '600px';

            $.cc.open({
                type : 2, //page层
                area : [ width, height ],
                title : '选择图标',
                maxmin : true,
                shade : 0.2, //遮罩透明度
                moveType : 1, //拖拽风格，0是默认，1是传统拖动
                content : url,
                btn : [ '确认','清除', '取消' ],
                yes : function(index, layero) {//确认按钮调用yes方法  取消按钮的方法为cancel
                    var win = getTopWindow();
                    var iframeWin = win[layero.find('iframe')[0]['name']];
                    var iconCls = iframeWin.getIconCls(index);
                    _this.setValue(iconCls);
                    $.cc.close(index);
                },
                btn2 : function(index, layero) {//确认按钮调用yes方法  取消按钮的方法为cancel
                    _this.setValue(null);
                    $.cc.close(index);
                }
            });
        })
    },
    setValue:function(value,change){

        var _this = this;
        if(isEmpty(change)){
            change = true;
        }
        if(isEmpty(value)){
            _this.value = null;
            _this.popup_input.html("");
        }else{
            _this.value = value;
            var _html = '<span class="glyphicon '+value+'" aria-hidden="true"></span>';
            _this.popup_input.html(_html);
        }

        if(change){
            _this._fire("onchange");
        }
    },
    _setStyle:function(){
        var _this = this;
        var width = _this.getOption('width');
        if(isNotEmpty(width)){
            _this.component.css({
                "width":width + "px"
            });
        }
    }
});
/******************************************************树形*****************************************************/

var onTreeClick = function(event, treeId, treeNode) {
    var $div = $(event.target).closest("div.ui-Tree");
    var objId = $div.attr("formId");
    var obj = _$.getById(objId);
    if(treeNode){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        var idField = obj.getOption("idField");
        var multiple = obj.getOption("multiple");
        if(!multiple) {
            var value = treeNode[idField];
            obj.setValue(value);
        }
    }
};
var onTreeCheck = function(event, treeId, treeNode) {
    var $div = $(event.target).closest("div.ui-Tree");
    var objId = $div.attr("formId");
    var obj = _$.getById(objId);

    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.getCheckedNodes(true);
    var idField = obj.getOption("idField");

    if(nodes != null && nodes.length >0){
        var values = [];
       for(var i=0;i<nodes.length;i++){
           var node = nodes[i];
           var value = node[idField];
           values.add(value)
       }
        obj.setValue(values.join(","));
    }else{
        obj.setValue("");
    }
};

_$.Tree=function (target){
    var _this = this;
    _$.Tree.superclass.constructor.call(_this,target);
};
_$.regClass("Tree",_$.Tree);

_$.extend(_$.Tree,_$.FormItem, {
    _cls:_$._clsPre + "Tree",
    _uiCls:_$._uiPreCls + "Tree",
    _attrProps:function(){
        var _this = this;
        var properties = _$.Tree.superclass._attrProps.call(_this);
        properties.addAll(["onchange","basePath","cascadeYes","cascadeNo","apiServer","call","idField","textField",'parentId','parentKey',"resultKey",{"multiple":"boolean","params":"object"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.Tree.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "basePath":"/base",
            "apiServer":"base",
            "idField":"id",
            "textField":"name",
            "multiple":false,
            "parentKey":"parentId",
            "resultKey":"nodes",
            "cascadeYes":"",
            "cascadeNo":""
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();
        var source='<ul id="tree_'+_this.id+'" class="ztree"></ul>';
        _this._replaceNode(source);
        _this.component = $(".ztree",_this.el);
        _this.initTree();
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    initTree:function(){
        var _this = this;
        _this._loadData(null,_this._editInit);
    },
    _init:function(){
        var _this = this;
        if(!_this._isEdit()){
            _this._initShow();
        }
    },
    _initShow:function(value){
        var _this = this;
        _this._loadData(value,_this._showInit);
    },
    _loadData:function(value,func){
        var _this = this;
        var parentKey = _this.getOption("parentKey");
        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");
        var params = _this.getOption("params");
        if(params == null){
            params = {};
        }
        _this.data = [];
        if(isNotEmpty(value)){
            params[idField] = value;

        }
        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询树形数据"
        };

        var url= basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    },

    _editInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var resultKey = _this.getOption("resultKey");
            var nodes = result.get(resultKey);
            _this.data=nodes;

            var idField = _this.getOption("idField");
            var textField = _this.getOption("textField");
            var parentKey = _this.getOption("parentKey");
            var multiple = _this.getOption("multiple");
            var cascadeYes = _this.getOption("cascadeYes");
            var cascadeNo = _this.getOption("cascadeNo");

            if(!multiple){
                var setting = {
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: idField,
                            pIdKey:parentKey
                        }
                    },
                    callback: {
                        onClick: onTreeClick
                    },
                    view: {
                        showLine:false
                    }
                };
            }else{
                var setting = {
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: idField,
                            pIdKey: parentKey,
                            name:textField
                        }
                    },
                    callback: {
                        onCheck: onTreeCheck
                    },
                    check: {
                        enable: true,
                        chkboxType: { "Y": cascadeYes, "N": cascadeNo }
                    },
                    view: {
                        showLine:false
                    }
                };
            }

            $.fn.zTree.init($("#tree_" + _this.id), setting, nodes);

            var initValue= _this.options["initValue"];
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if(isNotEmpty(initValue)){
                _this.setValue(initValue);
            }
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _showInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        var resultKey = _this.getOption("resultKey");
        if(state == 0){
            var nodes = result.get(resultKey);
            _this.data = nodes;
            var initValue = _this.getOption("initValue");
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if (isNotEmpty(initValue)){
                _this.setValue(initValue);
            }
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _bindEvents:function(){
        var _this = this;
        _$.Tree.superclass._getEvents.call(_this, ["onfocus","oninput","onblur","onchange"]);
        if(_this._isEdit()){
        }
    },
    _setStyle:function(){

    },

    setValue:function(value,change) {
        var _this = this;
        _this.value = value;
        if(isEmpty(change)){
            change = true;
        }

        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");
        var multiple = _this.getOption("multiple");
        var treeId = "tree_" + _this.id;
        var treeObj = $.fn.zTree.getZTreeObj(treeId);

        if(isEmpty(value) || isEmpty(_this.data) || _this.data.length == 0){
            _this.value = null;
        }else{
            _this.value = value;
            if (_this._isEdit()) {
                if(!multiple){
                    var nodes = treeObj.getNodesByParam(idField,value, null);
                    if(nodes != null && nodes.length>0){
                        var node = nodes[0];
                        if(node  != null){
                            treeObj.selectNode(node);
                        }
                    }
                }else{
                    treeObj.checkAllNodes(false);
                    var values = (value+"").split(",");
                    if(values != null && values.length>0){
                        for(var i=0;i<values.length;i++){
                            var val = values[i];
                            var nodes = treeObj.getNodesByParam(idField,val, null);
                            if(nodes != null && nodes.length>0){
                                var node = nodes[0];
                                if(node  != null){
                                    treeObj.checkNode(node, true, false);
                                }
                            }
                        }
                    }
                }

            } else {
                if(!multiple){
                     var flag = _this.data.some(function(item,i){
                        var id = item[idField];
                        var name = item[textField];

                        if(id == value){
                            _this.component.html(name);
                            return true;
                        }
                        return false;
                    });

                    if(!flag){
                        _this.value = null;
                        _this.component.html("");
                    }

                }else{
                    var values = (value+"").split(",");
                    if(values != null && values.length>0){
                        var names=[] ;
                        for(var i=0;i<values.length;i++){
                            var itemValue = values[i];

                            _this.data.each(function(item,i){
                                var id = item[idField];
                                var name = item[textField];
                                if(id == itemValue){
                                    names.add(name);
                                }
                            });
                        }
                        if(names.length>0){
                            _this.component.html(names.join(","));
                        }else{
                            _this.value = null;
                            _this.component.html('');
                        }
                    }else{
                        _this.value = null;
                        _this.component.html(names.join(","));
                    }

                }
            }
        }
        if(change){
            _this._fire("onchange");
        }
    },
    getValue:function(){
        var _this = this;
        return _this.value;
    }
});

/******************************************************文本框*****************************************************/
_$.CheckBox=function (target){
    var _this = this;
    _$.CheckBox.superclass.constructor.call(_this,target);
};
_$.regClass("CheckBox",_$.CheckBox);

_$.extend(_$.CheckBox,_$.FormItem, {
    _cls:_$._clsPre + "CheckBox",
    _uiCls:_$._uiPreCls + "CheckBox",
    _attrProps:function(){
        var _this = this;
        var properties = _$.CheckBox.superclass._attrProps.call(_this);
        properties.addAll(["onchange","idField","textField",{data:'object'}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.CheckBox.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "idField":"id",
            "textField":"name"
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();

        var source='<div class="pretty checkBox"></div>';
        _this._replaceNode(source);
        _this.component = $(".checkBox",_this.el);
        _this.el.addClass(_this._uiCls);
        _this._initCheckBox();
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    _initCheckBox:function(){
        var _this = this;
        var data = _this.getOption("data");
        _this.data = data;
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        var value = data[idField];
        var name = data[textField];
        var _html = '<input type="checkbox" value="'+value+'" /><label><i class="mdi mdi-check"></i>&nbsp;'+name+'</label>';
        _this.component.html(_html);
        _this.checkbox_input = $("input",_this.component);
        _this._bindCheckBoxEvent();
        _this._loadSuccess();
    },
    _init:function(){
        var _this = this;
        if(!_this._isEdit()){
            var data = _this.getOption("data");
            _this.data = data;
            var initValue= _this.options["initValue"];
            _this.setValue(initValue);
        }
        _this._loadSuccess();
    },
    _bindCheckBoxEvent:function(){
        var _this = this;
        _this.checkbox_input.bind("click",function(e){
            event['source'] = _this.component;
            event['value'] = _this.getValue();
            _this._clickHandler(event);
        });
    },
    setValue:function(value,change){
        var _this = this;
        if(isEmpty(change)){
            change = true;
        }
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        if(isEmpty(value) || isEmpty(_this.data)){
            _this.value = "";
            if(_this._isEdit()){
                _this.checkbox_input.prop("checked",false);
            }else{
                _this.component.html("")
            }
        }else{
            var orgi = _this.data[idField];
            var name = _this.data[textField];
          if(_this._isEdit()){
              if(orgi == value){
                  _this.value = value;
                  _this.checkbox_input.prop("checked",true);
              }else{
                  _this.value = null;
                  _this.checkbox_input.prop("checked",false);
              }
          }else{
              if(orgi == value){
                  _this.value = value;
                  _this.component.html(name)
              }else{
                  _this.value = null;
                  _this.component.html("")
              }
          }
        }
        if(change){
            _this._fire("onchange");
        }
    },
    _clickHandler:function(event){
        var _this = this;
        _this._fire("onclick",event);
        var original = isNotEmpty(_this.original)?_this.original:_this.getOption("initValue");
        var value = _this.getValue();
        if(original != value){
            _this.original=value;
            _this._fire("onchange",event);
        }
    },
    _sync:function(){
        var _this = this;
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        if(_this.checkbox_input.is(":checked")){
           _this.value =  _this.data[idField];
        }else{
            _this.value = null;
        }
    }
});

/******************************************************文本框*****************************************************/
_$.CheckBoxList=function (target){
    var _this = this;
    _$.CheckBoxList.superclass.constructor.call(_this,target);
};
_$.regClass("CheckBoxList",_$.CheckBoxList);

_$.extend(_$.CheckBoxList,_$.FormItem, {
    _cls:_$._clsPre + "CheckBoxList",
    _uiCls:_$._uiPreCls + "CheckBoxList",
    _attrProps:function(){
        var _this = this;
        var properties = _$.CheckBoxList.superclass._attrProps.call(_this);
        properties.addAll(["onclick","onchange","idField","textField","resultKey",{data:'object',"dataFilter":"function"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.CheckBoxList.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "idField":"id",
            "textField":"name",
            "basePath":"/base",
            "apiServer":"base",
            "call":"",
            "dataFilter":function(list){
                return list;
            }
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();

        var source='<div  class="CheckBoxList"></div>';
        _this._replaceNode(source);
        _this.component = $(".CheckBoxList",_this.el);
        _this._initCheckBoxList();
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    _initCheckBoxList:function(){
        var _this = this;
        _this._loadData(_this._editInit);
    },
    _init:function(){
        var _this = this;
        if(!_this._isEdit()){
            _this._initShow();
        }
    },
    _initShow:function(value){
        var _this = this;
        _this._loadData(_this._showInit);
    },
    _loadData:function(func){
        var _this = this;
        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var dictCode = _this.getOption("dictCode");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");
        var params = _this.getOption("params");
        if(params == null){
            params = {};
        }

        _this.data = [];
        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询下拉框条目"
        };

        var url= basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    },
    _editInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var list = result.get("list");
            _this.data = list;
            var dataFilter = _this.getOption("dataFilter");
            list = dataFilter.call(window,list);

            _this._setData(list);
            var initValue= _this.options["initValue"];
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if(isNotEmpty(initValue)){
                _this.setValue(initValue);
            }
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _showInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var resultKey = _this.getOption("resultKey");
            var list = result.get(resultKey);
            var dataFilter = _this.getOption("dataFilter");
            list = dataFilter.call(window,list);
            _this.data = list;
            var initValue = _this.getOption("initValue");
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if (isNotEmpty(initValue)){
                _this.setValue(initValue);
            }
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _setData:function(list){
        var _this = this;

        var multiple = _this.getOption("multiple");
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        _this.component.empty();
        if(list != null && list.length>0){
            for(var i=0;i<list.length;i++){
                var item = list[i];
                var value = item[idField];
                var name = item[textField];
                var _html='<div class="pretty o-primary"><input type="checkbox" name="checkbox_'+_this.id+'" value="'+value+'" /><label><i class="mdi mdi-check"></i>&nbsp;'+name+'</label></div>';
                _this.component.append(_html);
            }
        }

        var initValue= _this.options["initValue"];
        if(isNotEmpty(_this.value)){
            _this.setValue(_this.value);
        }else if(isNotEmpty(initValue)){
            _this.setValue(initValue);
        }
        _this._bindCheckEvent();
    },
    _bindCheckEvent:function(){
        var _this = this;
        if(_this._isEdit()){
            var event = {
                "name":_this.id
            };
            $(":checkbox",_this.component).unbind("click").bind("click",function(e){

                event['source'] = _this.component;
                event['value'] = _this.getValue();
                _this._clickHandler(event);
            });
        }
    },
    setValue:function(value,change) {
        var _this = this;
        _this.value = value;
        if(isEmpty(change)){
            change = true;
        }

        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        if(isEmpty(value) || isEmpty(_this.data) || _this.data.length == 0){
            _this.value = null
            if(!_this._isEdit()){
                _this.component.html("");
            }
        }else{
            _this.value = value;
            if (_this._isEdit()) {
                $(":checkbox",_this.component).prop("checked",false);
                var values = (value+"").split(",");
                if(values != null && values.length>0){
                    for(var i=0;i<values.length;i++){
                        var val = values[i];
                        $(":checkbox[value='"+val+"']",_this.component).prop("checked",true);
                    }
                }

            } else {
                var values = (value+"").split(",");
                if(values != null && values.length>0){
                    var names=[] ;
                    for(var i=0;i<values.length;i++){
                        var itemValue = values[i];

                        _this.data.each(function(item,i){
                            var id = item[idField];
                            var name = item[textField];
                            if(id == itemValue){
                                names.add(name);
                            }
                        });
                    }
                    if(names.length>0){
                        _this.component.html(names.join(","));
                    }else{
                        _this.value = null;
                        _this.component.html('');
                    }

                }else{
                    _this.value = null;
                    _this.component.html(names.join(","));
                }

            }
        }
        if(change){
            _this._fire("onchange");
        }
    },
    _clickHandler:function(event){
        var _this = this;
        _this._fire("onclick",event);
        var original = isNotEmpty(_this.original)?_this.original:_this.getOption("initValue");
        var value = _this.getValue();
        if(original != value){
            _this.original=value;
            _this._fire("onchange",event);
        }
    },
    _sync:function(){
        var _this = this;
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        var values = [];
        $(":checkbox",_this.component).each(function(){
            var $checkBox = $(this);
            if($checkBox.is(":checked")){
                var value = $checkBox.val();
                values.add(value);
            }

        });
        _this.value = values.join(",");
    },
    _setStyle:function(){
        var _this = this;
        var width = _this.getOption('width');
        if(isNotEmpty(width)){
            _this.component.css({
                "width":width + "px"
            });
        }
    }
});

/******************************************************文本框*****************************************************/
_$.CheckBoxListDict=function (target){
    var _this = this;
    _$.CheckBoxListDict.superclass.constructor.call(_this,target);
};
_$.regClass("CheckBoxListDict",_$.CheckBoxListDict);

_$.extend(_$.CheckBoxListDict,_$.CheckBoxList, {
    _cls:_$._clsPre + "CheckBoxListDict",
    _uiCls:_$._uiPreCls + "CheckBoxListDict",
    _attrProps:function(){
        var _this = this;
        var properties = _$.CheckBoxListDict.superclass._attrProps.call(_this);
        properties.addAll(["dictCode"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.CheckBoxListDict.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            'dictCode':'',
            "idField":"code",
            "call":"dict.selectByDict"
        });
    },
    _loadData:function(func){
        var _this = this;
        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var dictCode = _this.getOption("dictCode");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");
        var params = _this.getOption("params");
        if(params == null){
            params = {};
        }
        params["dictCode"]=dictCode;
        _this.data = [];

        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询下拉框条目"
        };

        var url= basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    }
});

/******************************************************文本框*****************************************************/
_$.RadioBoxList=function (target){
    var _this = this;
    _$.RadioBoxList.superclass.constructor.call(_this,target);
};
_$.regClass("RadioBoxList",_$.RadioBoxList);

_$.extend(_$.RadioBoxList,_$.FormItem, {
    _cls:_$._clsPre + "RadioBoxList",
    _uiCls:_$._uiPreCls + "RadioBoxList",
    _attrProps:function(){
        var _this = this;
        var properties = _$.RadioBoxList.superclass._attrProps.call(_this);
        properties.addAll(["onclick","onchange","idField","textField",{data:'object',"dataFilter":"function"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.RadioBoxList.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "idField":"id",
            "textField":"name",
            "basePath":"/base",
            "apiServer":"base",
            "dataFilter":function(list){
                return list;
            }
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();

        var source='<div  class="RadioBoxList"></div>';
        _this._replaceNode(source);
        _this.component = $(".RadioBoxList",_this.el);
        _this._initRadioBoxList();
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    _initRadioBoxList:function(){
        var _this = this;
        _this._loadData(_this._editInit);
    },
    _loadData:function(func){
        var _this = this;

        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");
        var params = _this.getOption("params");
        if(params == null){
            params = {};
        }
        _this.data = [];
        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询下拉框条目"
        };

        var url= basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    },

    _init:function(){
        var _this = this;
        if(!_this._isEdit()){
            _this._initShow();
        }
    },
    _initShow:function(value){
        var _this = this;
        _this._loadData(_this._showInit);
    },
    _editInit:function(result){

        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var list = result.get("list");
            var dataFilter = _this.getOption("dataFilter");
            list = dataFilter.call(window,list);
            _this.data = list;
            _this._setData(list);
            var initValue= _this.options["initValue"];
            _this.setValue(initValue);
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _showInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var list = result.get("list");
            var dataFilter = _this.getOption("dataFilter");
            list = dataFilter.call(window,list);
            _this.data = list;
            var initValue = _this.getOption("initValue");
            _this.setValue(initValue);
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _setData:function(list){
        var _this = this;
        var multiple = _this.getOption("multiple");
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        _this.component.empty();
        if(list != null && list.length>0){
            for(var i=0;i<list.length;i++){
                var item = list[i];
                var value = item[idField];
                var name = item[textField];
                var _html='<div class="pretty circle o-primary"><input type="radio" name="checkbox_'+_this.id+'" value="'+value+'" /><label><i class="mdi mdi-check"></i>&nbsp;'+name+'</label></div>';
                _this.component.append(_html);
            }
        }

        var initValue= _this.options["initValue"];
        if(isNotEmpty(_this.value)){
            _this.setValue(_this.value);
        }else if(isNotEmpty(initValue)){
            _this.setValue(initValue);
        }
        _this._bindRadioEvent();
    },
    _bindRadioEvent:function(){
        var _this = this;
        if(_this._isEdit()){
            var event = {
                "name":_this.id
            };

            $(":radio",_this.component).unbind("click").bind("click",function(e){

                event['source'] = _this.component;
                event['value'] = _this.getValue();
                _this._clickHandler(event);
            });
        }
    },
    setValue:function(value,change) {
        var _this = this;
        _this.value = value;
        if(isEmpty(change)){
            change = true;
        }

        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        if(isEmpty(value) || isEmpty(_this.data) || _this.data.length == 0){
            _this.value = null
            if(!_this._isEdit()){
                _this.component.html("");
            }
        }else{
            _this.value = value;
            if (_this._isEdit()) {
                $(":radio",_this.component).prop("checked",false);
                var values = (value+"").split(",");
                if(values != null && values.length>0){
                    for(var i=0;i<values.length;i++){
                        var val = values[i];
                        $(":radio[value='"+val+"']",_this.component).prop("checked",true);
                        break;
                    }
                }

            } else {
                var values = (value+"").split(",");
                if(values != null && values.length>0){
                    var names=[] ;
                    for(var i=0;i<values.length;i++){
                        var itemValue = values[i];

                        _this.data.each(function(item,i){
                            var id = item[idField];
                            var name = item[textField];
                            if(id == itemValue){
                                names.add(name);
                            }
                        });
                    }
                    if(names.length>0){
                        _this.component.html(names.join(","));
                    }else{
                        _this.value = null;
                        _this.component.html('');
                    }

                }else{
                    _this.value = null;
                    _this.component.html(names.join(","));
                }

            }
        }
        if(change){
            _this._fire("onchange");
        }
    },
    _bindEvents:function(){
        var _this = this;
        _$.RadioBoxList.superclass._getEvents.call(_this, ["onclick","onchange"]);

    },
    _clickHandler:function(event){
        var _this = this;
        _this._fire("onclick",event);
        var original = isNotEmpty(_this.original)?_this.original:_this.getOption("initValue");
        var value = _this.getValue();
        if(original != value){
            _this.original=value;
            _this._fire("onchange",event);
        }
    },
    _sync:function(){
        var _this = this;
        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");

        $(":radio",_this.component).each(function(){
            var $checkBox = $(this);
            if($checkBox.is(":checked")){
                _this.value = $checkBox.val();
            }

        });
    },
    _setStyle:function(){
        var _this = this;
        var width = _this.getOption('width');
        if(isNotEmpty(width)){
            _this.component.css({
                "width":width + "px"
            });
        }
    }
});

/******************************************************文本框*****************************************************/
_$.RadioBoxListDict=function (target){
    var _this = this;
    _$.RadioBoxListDict.superclass.constructor.call(_this,target);
};
_$.regClass("RadioBoxListDict",_$.RadioBoxListDict);

_$.extend(_$.RadioBoxListDict,_$.RadioBoxList, {
    _cls:_$._clsPre + "RadioBoxListDict",
    _uiCls:_$._uiPreCls + "RadioBoxListDict",
    _attrProps:function(){
        var _this = this;
        var properties = _$.RadioBoxListDict.superclass._attrProps.call(_this);
        properties.addAll(["dictCode"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.RadioBoxListDict.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            'dictCode':'',
            "idField":"code",
            "call":"dict.selectByDict"
        });
    },
    _loadData:function(func){
        var _this = this;

        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var dictCode = _this.getOption("dictCode");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");
        var params = _this.getOption("params");
        if(params == null){
            params = {};
        }
        params["dictCode"]=dictCode;
        _this.data = [];

        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询下拉框条目"
        };

        var url= basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    }
});

/******************************************************文本框*****************************************************/
/*
依赖
 <link href="/static/lib/datepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
 <script type="text/javascript" src="/static/lib/datepicker/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
 <script type="text/javascript" src="/static/lib/datepicker/js/locales/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
*/
_$.DateTimePicker=function (target){
    var _this = this;
    _$.DateTimePicker.superclass.constructor.call(_this,target);
};
_$.regClass("DateTimePicker",_$.DateTimePicker);

_$.extend(_$.DateTimePicker,_$.FormItem, {
    _cls:_$._clsPre + "DateTimePicker",
    _uiCls:_$._uiPreCls + "DateTimePicker",
    _attrProps:function(){
        var _this = this;
        var properties = _$.DateTimePicker.superclass._attrProps.call(_this);
        properties.addAll(["view","onchange","inputStyle"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.DateTimePicker.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            view:2
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();
        var source='<input type="text" class="DateTimePicker" />';
        _this._replaceNode(source);
        _this.component = $(".DateTimePicker",_this.el);
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this._initDatetimepicker();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    _initDatetimepicker:function(){
        var _this = this;
        var view = _this.getOption("view");
        if(0 == view){
            _this.component.datetimepicker({
                format: 'yyyy',
                'language':'zh-CN',
                startView:4,
                autoclose: 1,
                forceParse:0,
                minView:4
            });
        }else if(1 == view){
            _this.component.datetimepicker({
                format: 'yyyy-mm',
                'language':'zh-CN',
                startView:3,
                autoclose: 1,
                forceParse:0,
                minView:3
            });
        }else if(2 == view){
            _this.component.datetimepicker({
                format: 'yyyy-mm-dd',
                'language':'zh-CN',
                startView:2,
                autoclose: 1,
                forceParse:0,
                minView:2
            });
        }else if(3 == view){
            _this.component.datetimepicker({
                format: 'yyyy-mm-dd hh:ii:ss',
                'language':'zh-CN',
                startView:2,
                autoclose: 1,
                forceParse:0,
                minView:1
            });
        }else if(4 == view){
            _this.component.datetimepicker({
                format: 'hh:ii:ss',
                'language':'zh-CN',
                startView:1,
                autoclose: 1,
                forceParse:0,
                minView:0
            });
        }
    },
    _bindEvents:function(){
        var _this = this;
        _$.DateTimePicker.superclass._getEvents.call(_this, ["onblur","onchange"]);
        if(_this._isEdit()){
            var event = {
                "name":_this.id
            };

            _this.component.bind("blur",function(){
                event['source'] = _this.component;
                event['value'] = _this.getValue();
                _this._blurHandler(event);
            });
        }
    },
    _blurHandler:function(event){
        var _this = this;
        _this._fire("onblur",event);
        var original = isNotEmpty(_this.original)?_this.original:_this.getOption("initValue");
        var value = _this.getValue();
        if(original != value){
            _this.original=value;
            _this._fire("onchange",event);
        }
    },
    _setStyle:function(){
        var _this = this;
        var width = _this.getOption('width');
        if(isNotEmpty(width)){
            _this.component.css({
                "width":width + "px"
            });
        }
        var height =_this.getOption('height');
        if(isNotEmpty(height)){
            _this.component.css({
                "height":height + "px"
            });
        }
        var inputStyle = _this.getOption('inputStyle');
        if(isNotEmpty(inputStyle)){
            _$.css(_this.component,inputStyle);
        }
    }
});


/*
 依赖
 <script type="text/javascript"  src="/static/lib/jquery.layout/jquery.layout-latest.js"></script>

 <div class="ui-layout-center">
 xxx
 </div>
 <div class="ui-layout-west">
 xxx
 </div>
 <div class="ui-layout-north">
 xxx
 </div>
 <div class="ui-layout-south">
 xxx
 </div>
 <div class="ui-layout-east">
 xxx
 </div>


 $(function () {
 var myLayout = $("body").layout(
 {
     applyDefaultStyles: true,//应用默认样式
     scrollToBookmarkOnLoad: false,//页加载时滚动到标签
     showOverflowOnHover: false,//鼠标移过显示被隐藏的，只在禁用滚动条时用。
     north__closable: false,//可以被关闭
     north__resizable: false,//可以改变大小
     north__size: 50,//pane的大小
     spacing_open: 8,//边框的间隙
     spacing_closed: 60,//关闭时边框的间隙
     resizerTip: "可调整大小",//鼠标移到边框时，提示语
     resizerCursor:"resize-p",// 鼠标移上的指针样式
     resizerDragOpacity: 0.9,//调整大小边框移动时的透明度
     maskIframesOnResize: "#ifa",//在改变大小的时候，标记iframe（未通过测试）
     sliderTip: "显示/隐藏侧边栏",//在某个Pane隐藏后，当鼠标移到边框上显示的提示语。
     sliderCursor: "pointer",//在某个Pane隐藏后，当鼠标移到边框上时的指针样式。
     slideTrigger_open: "dblclick",//在某个Pane隐藏后，鼠标触发其显示的事件。(click", "dblclick", "mouseover)
     slideTrigger_close: "click",//在某个Pane隐藏后，鼠标触发其关闭的事件。("click", "mouseout")
     togglerTip_open: "关闭",//pane打开时，当鼠标移动到边框上按钮上，显示的提示语
     togglerTip_closed: "打开",//pane关闭时，当鼠标移动到边框上按钮上，显示的提示语
     togglerLength_open: 100,//pane打开时，边框按钮的长度
     togglerLength_closed: 200,//pane关闭时，边框按钮的长度
     hideTogglerOnSlide: true,//在边框上隐藏打开/关闭按钮(测试未通过)
     togglerAlign_open: "left",//pane打开时，边框按钮显示的位置
     togglerAlign_closed: "right",//pane关闭时，边框按钮显示的位置
     togglerContent_open: "<div style='background:red'>AAA</div>",//pane打开时，边框按钮中需要显示的内容可以是符号"<"等。需要加入默认css样式.ui-layout-toggler .content
     togglerContent_closed: "<img/>",//pane关闭时，同上。
     enableCursorHotkey: true,//启用快捷键CTRL或shift + 上下左右。
     customHotkeyModifier: "shift",//自定义快捷键控制键("CTRL", "SHIFT", "CTRL+SHIFT"),不能使用alt
     south__customHotkey: "shift+0",//自定义快捷键（测试未通过）
     fxName: "drop",//打开关闭的动画效果
     fxSpeed: "slow"//动画速度
     //fxSettings: { duration: 500, easing: "bounceInOut" }//自定义动画设置(未通过测试)
     //initClosed:true,//初始时，所有pane关闭
     //initHidden:true //初始时，所有pane隐藏
     //onresize: ons,//调整大小时调用的函数
     //onshow_start: start,
     //onshow_end: end
     /*
     其他回调函数

     显示时调用
     onshow = ""
     onshow_start = ""
     onshow_end = ""
     隐藏时调用
     onhide = ""
     onhide_start = ""
     onhide_end = ""
     打开时调用
     onopen = ""
     onopen_start = ""
     onopen_end = ""
     关闭时调用
     onclose = ""
     onclose_start = ""
     onclose_end = ""
     改变大小时调用
     onresize = ""
     onresize_start = ""
     onresize_end = ""
}
);
});

 */
_$.Layout=function (target,opts){
    var _this = this;
    _this.opts = opts;
    _$.Layout.superclass.constructor.call(_this,target);

};

_$.extend(_$.Layout,_$.Component, {
    _attrProps:function(){
        var _this = this;
        var properties = _$.Layout.superclass._attrProps.call(_this);
        properties.addAll([]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.Layout.superclass._attrOpts.call(_this);
        return $.extend(true,opts,_this.opts,{
            applyDefaultStyles: true
        });
    },
    _create:function(){
       var _this = this;
        _this.el.layout(_this.options);
    }
});
/******************************************************文本框*****************************************************/
_$.Button=function (target){
    var _this = this;
    _$.Button.superclass.constructor.call(_this,target);
};
_$.regClass("Button",_$.Button);

_$.extend(_$.Button,_$.Component, {
    _cls:_$._clsPre + "Button",
    _uiCls:_$._uiPreCls + "Button",
    _attrProps:function(){
        var _this = this;
        var properties = _$.Button.superclass._attrProps.call(_this);
        properties.addAll(["clazz","iconCls","buttonText","onclick"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.Button.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "clazz":"btn btn-default",
            "iconCls":""
        });
    },
    _create:function(){
        var _this = this;
        var clazz = _this.getOption("clazz");
        var iconCls = _this.getOption("iconCls");
        var buttonText = _this.getOption("buttonText");
        var source='<button type="button" class="'+clazz+'"><span class="glyphicon '+iconCls+'"></span>'+buttonText+'</button>';

        _this._replaceNode(source);
        _this.component = _this.el;
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this._init();
        _this._bindEvents();
    },
    _init:function(){
        var _this = this;

        _this._loadSuccess();
    },
    _bindEvents:function(){
        var _this = this;
        _$.Button.superclass._getEvents.call(_this, ["onclick"]);
        var event = {
            "name":_this.id
        };
        _this.component.bind("click",function(){
            event['source'] = _this.component;
            _this._fire("onclick",event);
        });
    }
});

/******************************************************文本框*****************************************************/
_$.ButtonAuth=function (target){
    var _this = this;
    _$.ButtonAuth.superclass.constructor.call(_this,target);
};
_$.regClass("ButtonAuth",_$.ButtonAuth);

_$.extend(_$.ButtonAuth,_$.Component, {
    _cls:_$._clsPre + "ButtonAuth",
    _uiCls:_$._uiPreCls + "ButtonAuth",
    _attrProps:function(){
        var _this = this;
        var properties = _$.ButtonAuth.superclass._attrProps.call(_this);
        properties.addAll(["clazz","press","iconCls","buttonText","onclick"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.ButtonAuth.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "clazz":"btn btn-default",
            "iconCls":"",
            "press":""
        });
    },
    _create:function(){
        var _this = this;
        var clazz = _this.getOption("clazz");
        var iconCls = _this.getOption("iconCls");
        var buttonText = _this.getOption("buttonText");
        var onclick = _this.getOption("onclick");

        var source='<button type="button" class="'+clazz+'" onclick="'+onclick+'"><span class="glyphicon '+iconCls+'"></span>'+buttonText+'</button>';

        _this._replaceNode(source);
        _this.component = _this.el;
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this._init();
        _this._bindEvents();
    },
    _init:function(){
        var _this = this;
        var flag = _this._hasAuth();
        if(!flag){
            _this.component.hide();
        }
        _this._loadSuccess();
    },
    _hasAuth:function(){
        var _this = this;
        var press =_this.getOption("press");
        if(isEmpty(press)){
            return true;
        }

        if(isEmpty(authorityes) || authorityes.length == 0){
            return false;
        }

        for(var i=0;i<authorityes.length;i++){
            var item = authorityes[i];
            var code = item["code"];

            if(code == press){
                return true;
            }
        }
      return false;
    },
    _bindEvents:function(){

    }
});

/******************************************************文本框*****************************************************/
_$.FileUploadLogo=function (target){
    var _this = this;
    _$.FileUploadLogo.superclass.constructor.call(_this,target);
};
_$.regClass("FileUploadLogo",_$.FileUploadLogo);

_$.extend(_$.FileUploadLogo,_$.FormItem, {
    _cls:_$._clsPre + "FileUploadLogo",
    _uiCls:_$._uiPreCls + "FileUploadLogo",
    _attrProps:function(){
        var _this = this;
        var properties = _$.FileUploadLogo.superclass._attrProps.call(_this);
        properties.addAll(["systemCode","moduleId","bizBase","onchange"]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.FileUploadLogo.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "domainUrl":"http://oyxr5nbal.bkt.clouddn.com/",
            "getTokenUrl":"/base/file/getuploadToken",
            "defaultImg":"/base/images/timg.jpg",
            "domain":"/mytest",
            "systemCode":"base",
            "moduleId":"system",
            "bizBase":""
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();
        var defaultImg = _this.getOption("defaultImg");
        var source='<div class="input-file" type="button"  onclick="">' +
            '<img class="showImage" src="'+defaultImg+'" />' +
            '<input type="file" style="height:50px;width:100%;" id="logo_'+_this.id+'" />' +
            '<div  class="progress" style="display: none;width: 200px;">' +
            '<div  class="progressBar" aria-valuenow="0" aria-valuemax="100" aria-valuemin="0" style="width:0%;">' +
            '</div></div></div>';

        _this._replaceNode(source);
        _this.component = $(".showImage",_this.el);
        _this.progress = $(".progress",_this.el);
        _this.progressBar = $(".progressBar",_this.el);
        _this.el.addClass(_this._uiCls);
        _this._initUpload();
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    _showModel:function(){
        var _this = this;
        _this._clearEdit();
        var defaultImg = _this.getOption("defaultImg");
        var source='<div class="showDiv"><img class="showImage" src="'+defaultImg+'"/></div>';
        _this._replaceNode(source);
        _this.component = $(".showImage",_this.el);
        _this.el.addClass(_this._uiCls);
        _this.el.addClass(_this._spanCls);
        _this.setOption("model",_SHOW_);
        _this._init();
    },
    _initUpload:function(){
        var _this = this;
        var getTokenUrl = _this.getOption("getTokenUrl");
        var domain = _this.getOption("domain");
        var option = {
            runtimes : "html5,html4", // 上传模式，依次退化
            browse_button : "logo_" + _this.id, // 上传选择的点选按钮，必需
            uptoken_url :getTokenUrl, // Ajax请求uptoken的Url，强烈建议设置（服务端提供）
            get_new_uptoken : false, // 设置上传文件的时候是否每次都重新获取新的uptoken
            domain :domain, // bucket域名，下载资源时用到，必需
            max_file_size : "100mb", // 最大文件体积限制
            max_retries : 2, // 上传失败最大重试次数
            chunk_size : "4mb", // 分块上传时，每块的体积
            auto_start : true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
            init : {
                Key : key,
                'FileUploaded' : function(up, file, info) {
                    _this.progress.fadeOut();
                    var currentFileName = eval("(" + info + ")").key;

                    var domainUrl = _this.getOption("domainUrl");
                    var callUrl = domainUrl + currentFileName + "?" +new Date().getTime();

                    var systemCode = _this.getOption("systemCode");
                    var moduleId = _this.getOption("moduleId");
                    var bizBase = _this.getOption("bizBase");

                    var f = {
                        "systemCode":systemCode,
                        "moduleId":moduleId,
                        "bizBase":bizBase,
                        "origiName" : file.name,
                        "currentFileName" : currentFileName,
                        "callUrl" : callUrl,
                        "fileType" : file.type,
                        "fileSize" : _this.getSize(file.size)
                    };
                    _this.setValue(JSON.stringify([f]));
                },
                'FilesAdded' : function(up, files) {},
                'BeforeUpload' : function(up, file) {
                    _this.progress.fadeIn();
                },
                'UploadProgress' : function(up, file) {
                    _this.progressBar.css("width", file.percent + "%");
                },
                'Error' : function(up, err, errTip) {
                    _this.progress.fadeOut();
                    console.log(up);
                    console.log(err);
                    console.log(errTip);
                    alert("上传文件出错");
                }
            }
        };
        var qiniuInstance = new QiniuJsSDK();
        var uploader = qiniuInstance.uploader(option);
    },
    getSize:function(size) {
        if (size < 1000) {
            return size + " BYTE";
        }
        size = (size / 1000).toFixed(2);
        if (size < 1000) {
            return size + " KB";
        }
        size = (size / 1000.0).toFixed(2);
        return size + " MB";
    },
    setValue:function(value){
        var _this = this;
        if(isEmpty(value)){
            _this.value = null;
            _this.component.attr("src",defaultImg);
        }else{
            _this.value = value;
            var arr = JSON.parse(value);
            if(arr.length>0){
                var f = arr[0];
                var imgUrl;
                if (f.fileType.indexOf("image") > -1) {
                    imgUrl = f.callUrl;
                } else {
                    var defaultImg = _this.getOption("defaultImg");
                    imgUrl = defaultImg;
                }
                _this.component.attr("src",imgUrl);

            }else{
                _this.value = null;
                _this.component.attr("src",defaultImg);
            }
        }
    },
    getValue:function(){
        var _this = this;
        return _this.value;
    }
});
